Precision problem with stringstream and double [duplicate]
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?
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.
精彩评论