简体   繁体   中英

convert char * to double,without losing precision in c

I need some help. I have to convert and STORE a char * into a double or long double without losing precision.

Indeed, i tried to use strtold and atof methods (also strtold ), but these methods are rounding the value.

For example:

char * key  ="39.7519707";

double ld =strtod((char*)key,NULL);

printf("%lf", ld);

prints : 39.751971

but printf("%6.7f",ld) gives me the right value but I couldn't store into a variable.

First of all, you only need %f format specifier to print a double .

Then, you're not losing precision by making use of strtod() , the output representation is the problem with how you use printf() with %f format specifier.

As per C11 , chapter §7.21.6.1, fprintf()

[...] If the precision is missing, it is taken as 6;[...]

Next, when you did

printf("%6.7f",ld);

the precision became 7 and it outputs the value you expect to see.

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