Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help rounding to two decimal places

Status
Not open for further replies.

p1kn1c

Programmer
Sep 29, 2006
4
CA
Hi, what is the best way to round a double to two decimal places?

ie, if i had the number 77.786 i would want it rounded to 77.79.


I dont want a way to just display this number as two decimal places but to keep it like that so any time i use it it will be 77.79.

Also i cant know anything about the number, so there is no way of knowing if it is 77.786...or 7777777.554.

Thanks for any help.
 
Float point numbers (float and double) are not decimal numbers: they are binary approximations only. So you can't round these numbers exactly. Strictly speaking, 0.1, 0.01, 0.001 etc (double constants) are not equal to rational numbers 1/10, 1/100, 1/1000. No native decimal arithmetics in C and C++ languages. Have no illusions about this matter.

You may use this logic to round a double to two decimal places (for positive numbers):
Code:
double fr100(double x)
{
  double f, xi, xf;

  xf = modf(x,&xi);
  f = floor(xf*100+0.5)/100.0;
  return xi + f;
}
 
Here is another way.
for 2dp set PRECISION to 0.01 for 4dp 0.0001 etc.
Code:
double myRemainder = fmod(myValue, PRECISION);
if (myRemainder > ( 0.5 * PRECISION ))
{
    myValue = (myValue - myRemainder + PRECISION);
}
else
{
    myValue = (myValue  - myRemainder);
}
O.B.
 
> I dont want a way to just display this number as two decimal places but to keep it like that so any time i use it it will be 77.79.
Then you're out of luck, floating point numbers are not the thing to use for the reason ArkM states.
In particular, seek out David Goldberg's paper at the end.

If you really want exactly 2dp all the time, then multiply everything by 100, then use %100 and /100 to extract the relevant quantities. Addition remains easy, but multiply becomes more interesting.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top