简体   繁体   中英

How to convert a string to a double with 6-digit precision in C++?

I want to know how to convert a string like "1234.123456" to double or float . I need at least 3 digits precision (ie 3 digits after the decimal point, regardless of the number of digits before the point).

The exact value 1234.123456 isn't representable in any of the usual machine floating point formats. All you can do is choose how much accuracy you need, and use it. (On most modern machines, double has 16 digits precision. But that still doesn't mean that all 16 digit values are exactly representable.)

As for the conversion, just do what you would do to convert any type:

std::istringstream s( "1234.123456" );
double d;
s >> d;

And read http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html . It will explain the basic minimum you need to know in order to safely use machine floating point.

#include<stdlib.h> 

int main()
{
    double dnum = atof( "1234.123456" ) ;

    printf ( "%f\n" , dnum ) ;

    return 0 ;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM