views:

316

answers:

2

I have no problem converting "normal" double values, but I can't convert numeric_limits<double>::max() or DBL_MAX string representations?

std::string max = "1.79769313486232e+308";

std::istringstream stream(max);
double value;

// enters here, failbit is set
if (!(stream >> value))
+10  A: 

Could it be something like the actual value of DBL_MAX isn't exactly representable in exponential notation with 16 decimal places (say the decimal value is very slightly larger than the two based represenation) but initializing a double with the DBL_MAX will nevertheless set the correct value (due to rounding). std::istringstream may be a little bit more pickish.

EDIT: Actually I found that the value of DBL_MAX in my compiler is 1.7976931348623158e+308 which works fine for me to stream. Your number is rounded and slightly larger, hence the failure.

EDIT2: The exact value of DBL_MAX in decimal form is given by (2 ^ (1023 - 52)) * (2 ^ 53 - 1) which isn't representable with 16 decimal places.

Andreas Brinck
Yep ... I checked, and I was about to answer the same thing! You got to be really careful with these things ...
PierreBdR
You are right, for some reason my value was wrong. DBL_MAX is 1.7976931348623158e+308
Nikola Smiljanić
"the actual value of DBL_MAX isn't exactly representable". The actual value of DBL_MAX is an integer, it's exactly representable in any base. Just not necessarily representable in exponential notation with 16 decimal places. So we know what you mean, but it's not quite what you said ;-)
Steve Jessop
@Steve Yeah, that's what I meant, I stole your line from the comment and updated the answer, hope you dont mind ;)
Andreas Brinck
+1  A: 

if you use

double v = 1.79769313486232e+308;
cout << v << endl;

it would give you inf. that means the literal number is actually exceeds double now.

Yin Zhu