Public Group

# Some clarification about string to double conversion

This topic is 2159 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello,

I have the following piece of code:

string ss = findNodeValue( str, "Horizon");
cout << "ss is: " << ss << endl;
double dd = atof( ss.c_str());
cout << "dd is: " << dd << endl;


When the value of 'ss' is printed, I find it prints 1.0, but when the value of 'dd' is printed, it prints 1 whereas it is supposed to print 1.0. Could any one help me figure out what the problem is.

##### Share on other sites

Why is it "supposed" to print 1.0? The value "1" can be represented exactly in a double, and you didn't specify any particular format, so it just prints that number in the most natural way possible, that is, "1" (actually, I think it is implementation dependent). If ss contained "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000" would you argue that dd should also be printed exactly the same?

If you want to obtain a certain precision/number of digits, you can tell cout that by passing stream modifiers, e.g. std::setprecision, etc..

##### Share on other sites

cout truncates the .0 because it's unnecessary to represent the value. You'll have to set a fixed floatfield and set the precision to one desired. Explanation can be found here:

http://www.cplusplus.com/reference/ios/ios_base/precision/

Edit: @Bacterius, Dem ninja skillz XD

Edited by boogyman19946

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 11
• 15
• 21
• 26
• 11