Reputation: 563
I'm reading in a value from a file to a double, which was written out as a double (625.20)
The double is coming in as: 625.20000000000005
I have tried near everything (including everything I was able to find on StackExchange) to get this to drop the digits after hundredths, but to no avail.
I've tried using floor, I've tried multiplying by 100 then casting to an int then casting back to double, nothing seems to work.
Any ideas?
Thanks!
Upvotes: 0
Views: 2060
Reputation: 1879
You can use decimal precision from to format floating-point values on output operations.
#include <iostream>
#include <string>
#include <iomanip>
int main()
{
double f =3.14159;
std::cout << std::setprecision(4) << f << '\n';
}
Result: 3.142
Upvotes: 1
Reputation: 65264
625.20 is not representable as a double - so the closest representable value is chosen, which is somewhere around 625.20000000000005.
Basic rule of thumb:
int
with a multiplicative factor of 10^n or a builtin construct if availableUpvotes: 2