1

Possible Duplicate:
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?

Here is my code

#include <sstream>
#include <iomanip>
#include <string>
#include <iostream>


int main(int ac, char **av)
{
  if (ac > 1)
    {
      std::string input = av[1];
      std::stringstream ss;
      double output;
      ss << input;
      ss >> output;
      std::cout << std::fixed << std::setprecision(2) << output << std::endl;
    }
}

I'm trying to convert a string to a double using stringstreams.

It works, but it acts very weirdly when using very big numbers:

./a.out 999999999999999999999999
999999999999999983222784.00

./a.out 42
42.00

How can i handle all double values?

Community
  • 1
  • 1
Intrepidd
  • 19,772
  • 6
  • 55
  • 63
  • 3
    How is this an exact duplicate? The other thread is about accuracy with recurring binary digits. This threads is about the limits of precision. It's subtly different. – Lightness Races in Orbit Feb 20 '11 at 18:50

1 Answers1

6

You can't handle "all double values" with arbitrary precision. In your case, you have about 15 decimal digits of precision. Write std::numeric_limits<double>::digits10 to the console and you'll see.

Take a read through this guide to floating-point arithmetic.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055