简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM