Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ conversion of double to a fixed point with minimum number of non-zero digits

Tags:

c

double

multiple fixed-point decimal numbers are mapped to the same double value. For example:

double d1 = 132.24;
double d2 =  132.24000000000001;

d1 and d2 have the same binary value.

When converting d1 (or d2, they have the same value) to string using ostream with 14 digits of precision, it is converted to: 132.24000000000001 .

Is there a way/library that supports conversion from double->string, where the string is the fixed-point value with a minimal number of non-zero digits and that is a valid conversion ? i.e. in this case converting d1 to a string will return 132.24000000000000 (shown with 14 digits precision)

like image 284
Navit F Avatar asked Oct 30 '22 19:10

Navit F


1 Answers

The library https://github.com/floitschG/double-conversion provides the DoubleToStringConverter::DoubleToAscii method with the SHORTEST option: "SHORTEST: produce the least amount of digits for which the internal identity requirement is still satisfied."

Thanks a lot to iwillnotexist-idonotexist for pointing me to the right direction.

like image 64
Navit F Avatar answered Nov 08 '22 09:11

Navit F