开发者

How to set floating point precision inside a variable

开发者 https://www.devze.com 2023-02-17 03:34 出处:网络
I am currently working a program where I need to calculate a rounded value to only 2开发者_JS百科 digits after a floating point.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消