0

Can someone please answer

How can we round to or round up to the nearest integer with decimal places number or fraction in C++?

13th Jun 2018, 9:43 AM
Au Shu fan
Au Shu fan - avatar
2 Answers
+ 4
Suppose this double d = 2.54; Here, you have 3 choices. 1. round up (ceil operation). 2. round down (floor operation). 3. round to the nearest int (adding 0.5 to d and casting it to int) The first two are obvious enough so long as you include math header to your project and use ceil(d) and floor(d) functions. The third one, has no built-in function, so you'd implement it as a utility function. int round(double x) { return static_cast<int>(x + 0.5); } int main() { double d = 2.54; int toInt = round(d); }
13th Jun 2018, 10:00 AM
Babak
Babak - avatar
+ 4
It's worthy to mention that, C language (particularly math.h header file) has numerous built-in round functions and macros to work with. See the following documentation. Defined in headerĀ <math.h> floatĀ Ā  Ā  Ā  roundf(Ā floatĀ argĀ ); (1)(since C99) doubleĀ Ā  Ā  Ā round(Ā doubleĀ argĀ ); (2)(since C99) longĀ doubleĀ roundl(Ā longĀ doubleĀ argĀ ); (3)(since C99) Defined in headerĀ <tgmath.h> #define round( arg ) (4)(since C99) Defined in headerĀ <math.h> longĀ Ā  Ā  Ā lroundf(Ā floatĀ argĀ ); (5)(since C99) longĀ Ā  Ā  Ā lround(Ā doubleĀ argĀ ); (6)(since C99) longĀ Ā  Ā  Ā lroundl(Ā longĀ doubleĀ argĀ ); (7)(since C99) Defined in headerĀ <tgmath.h> #define lround( arg ) (8)(since C99) Defined in headerĀ <math.h> longĀ longĀ llroundf(Ā floatĀ argĀ ); (9)(since C99) longĀ longĀ llround(Ā doubleĀ argĀ ); (10)(since C99) longĀ longĀ llroundl(Ā longĀ doubleĀ argĀ ); (11)(since C99) Defined in headerĀ <tgmath.h> #define llround( arg ) (12)(since C99)
13th Jun 2018, 10:53 AM
Babak
Babak - avatar