How can I round floats up to any number of decimal points?
For instance.. if I have 34.52348.. I could call the function, something like round(24.52348,2) to round it up to 24.52... Maybe there's a function I don't know about... please help.
This is a discussion on Rounding numbers up... within the C++ Programming forums, part of the General Programming Boards category; How can I round floats up to any number of decimal points? For instance.. if I have 34.52348.. I could ...
How can I round floats up to any number of decimal points?
For instance.. if I have 34.52348.. I could call the function, something like round(24.52348,2) to round it up to 24.52... Maybe there's a function I don't know about... please help.
~void
It could be done with a function if you put the float into a char array, go through each one until you find the decimal, then go however many you need after the decimal and round up or down depending on the last digit.
I don't know of any standard C++ function to do it, but a function like I described above wouldn't be hard to write.
#include <cmath>
// ...
const float pi = 3.14159;
int piIsExactly3 = std::ceil(pi);
In short, use std::ceil() found in <cmath>
To round to a whole number, either subtract .5 and use ceil() or add .5 and use floor().
e.g., 1.4 + .5 = 1.9, floor(1.9) = 1 // actually 1.0
1.6 + .5 = 2.1, floor (2.1) = 2
Truth is a malleable commodity - Dick Cheney
...and to round to n decimal places, multiply by 10^n, round, then divide by 10^n
Claus Hetzer
Compiler: Borland 5.5 (on Windows)
Solaris CC (on Unix)
Known Languages: C++, MATLAB, Perl, Java
Actually, it's kind of tough to round 34.52348 to 24.52Originally posted by void
How can I round floats up to any number of decimal points?
For instance.. if I have 34.52348.. I could call the function, something like round(24.52348,2) to round it up to 24.52... Maybe there's a function I don't know about... please help.
Using my previous example, you could add .005 and then use floor(). The number of zeros before the five is the number of decimal places you want to round to. Possibly the binary inexactness of floating point numbers will give errors with decimal places, not sure there.
Truth is a malleable commodity - Dick Cheney