Irongrave
Irongrave

Reputation: 563

How can I convert a double to two decimal places?

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

Answers (2)

Marko Tunjic
Marko Tunjic

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

Eugen Rieck
Eugen Rieck

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:

  • if you are fine with these errors, use floats, then choose the format of your choice for output
  • if you need a fixed precision after the decimal point, use int with a multiplicative factor of 10^n or a builtin construct if available

Upvotes: 2

Related Questions