shushu
shushu

Reputation: 21

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 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?

Upvotes: 2

Views: 16508

Answers (4)

Naresh
Naresh

Reputation: 678

    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

Upvotes: 4

ChrisWue
ChrisWue

Reputation: 19020

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.

Upvotes: 0

fbafelipe
fbafelipe

Reputation: 4952

You can do this:

a = roundf(a*100)/100;

Upvotes: 1

Mark B
Mark B

Reputation: 96233

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.

Upvotes: 5

Related Questions