Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
double var = 79999.95;
cout << var << endl;

output I m getting is 79999.9, But I want the op to be 79999.95. I want the accurate precesion without rounding off.I know that setprecision(2) will print the output as 79999.95.But since I want to use that value (79999.95)for further computation, So how can I get the val as 79999.95 ,since I think that setprecesion is only printing the value.

What I have tried:

I have tried of <double = floor((val * 1000) +0.5)/ 1000; >
Posted
Updated 15-Jun-18 0:04am

There are two things to observe with floating point values:
  1. They can not represent most values exactly
  2. Printed values are rounded to a specified or default resolution which might be affected by the above
79999.95 is one of the values where the first point applies. It can't be represented exactly with a double. The stored value is 79999,949999999997 which can be verified by setting a corresponding output precision (17 significant digits). For a single precision float, the stored value would be 79999,95313.

The limited resolution and inaccuracy is not a problem for simple mathematic operations. But it might become a problem with complex operations where rounding errors can accumulate. Then the algorithm implementation has to take care of that.

The problem of showing a probably wrong rounded value is no problem when knowing about the precision of the value itself. And you should know that for your input values.

Related reads:
The Floating-Point Guide[^]
What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]
 
Share this answer
 
Print it into a string buffer and you are done.
C++
char s[20];
sprint(s,"%0.2f",var);
cout << s << endl;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900