how to rounding

I have a number a = 12.3456, I need to rounding. Setprecision function only shows the rounding on the screen. I need rounding Can store in another, as I do?

for 3 digits:

104.487111->104

tks
Last edited on
Since I never really had a need to round a floating-point number to the nearest integer, my solution might be severely overcomplicated, however... maybe not.

Try getting the remainder of a division of your number by 1, and checking if it's less than 0.5. If it is, cast to an int, else, cast to an int and add one. fmod(), which is a useful little function that you might find useful for getting your remainder, can be found in <cmath>.

http://www.cplusplus.com/reference/clibrary/cmath/fmod/

Happy coding!

-Albatross
Last edited on
for 104.487111->104 it is int x = int(104.487111 + 0.5)

is for any number and any precision,

eg
number:
12.23
precision:
2
rounded: 12
continue? 1

number:
12.23
precision:
3
rounded: 12.2
continue? 1

number:
12.23
precision:
4
rounded: 12.23
continue? 1

number:
12.56
precision:
2
rounded: 13
continue? 1

number:
12.56
precision:
3
rounded: 12.6
continue? 1

number:
12.56
precision:
4
rounded: 12.56
Last edited on
Easiest way to round a number is to cast it to an integer. Example:

1
2
double x = 12.57;
int y = (int)(x + 0.5);


Since converting a double to integer would just round the number down automatically, you add 0.5 to it first. That way, if you have a number above .5, such as .6, adding .5 to it would increment to the next whole number, then round down to that number. So...


12.57 + 0.5 = 13.07
13.07 -> INT = 13


And for numbers where the numbers after the decimal are less than .5:


12.35 + 0.5 = 12.85
12.85 -> INT = 12
That doesn't work for negative numbers.
Topic archived. No new replies allowed.