0

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!

Irongrave
  • 553
  • 1
  • 5
  • 15
  • 6
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). If you read that article, you will know that it's simply not possible. Instead you should *print* it with only two decimals (might want to read about [I/O manipulators](http://en.cppreference.com/w/cpp/header/iomanip) for that). – Some programmer dude Apr 20 '14 at 20:56
  • What does "coming in as" mean? How are you displaying it now? Use the `%.2lf` format if you're using a `printf`. – lurker Apr 20 '14 at 20:56
  • 1
    If you need to *store* the value `625.20` in a `double`, you can't. If you want to *display* it as `625.20`, there are several ways you can do that. – Keith Thompson Apr 20 '14 at 21:08
  • 2 d.p.? Sounds a lot like http://stackoverflow.com/questions/149033/best-way-to-store-currency-values-in-c – johnsyweb Apr 20 '14 at 21:12
  • Thanks for the responses guys. It's being read in from a binary file using fstream.read((char*)&doublevariable), sizeof(double)) into a double. I wasn't having any problems displaying it (I'd use setprecision(2) and fixed) but it appeared to be causing some problems in a constructor I was using. I'm all set now though -- thanks again. – Irongrave Apr 20 '14 at 23:17

2 Answers2

2

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
Esenti
  • 707
  • 6
  • 12
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
1

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

Marko Tunjic
  • 1,811
  • 1
  • 14
  • 15