How to set floating point precision inside a variable
I am currently working a program where I need to calculate a rounded value to only 2开发者_JS百科 digits after a floating point. Say, I have declared
float a;
If a = 3.555
then it would store a = 3.56
, rounding up.
For a = 3.423
, the value of a would be a = 3.423
, no change.
I can do this to print output, but what I need to do when storing it into a variable and use that variable for some other calculation?
If you need two digits after the decimal point, don't use floating point. Use a fixed point number instead. For example, just use an integer that's 100 times larger than the decimal number you want to represent. Trying to fit a base 2 floating point number into rounding rules like this just isn't going to produce satisfactory results for you.
double d = 5000.23423;
d = ceil(d*100)/100;
cout << d << endl; // prints : 5000.24
double e = 5000.23423;
e = floor(e*100)/100;
cout << e << endl; // prints : 5000.23
You can do this:
a = roundf(a*100)/100;
How about
#include <math.h>
int main ()
{
double a, f, i;
a = 3.436;
f= modf(a, &i);
a = i + roundf(f* 100.0) / 100.0;
return 0;
}
Operates on doubles but avoids scaling the whole number.
Update: Added the missing division.
精彩评论