For example, if you use single precision floats, then you need up to 9 digits of decimal precision to uniquely identify a float. So you would need to use a printf pattern like %.9g to print it. But then 0.1 would be output as 0.100000001, which is ugly. So a common approach is to round to 6 decimal digits: If you use %.6g, you are guaranteed that any decimal input up to 6 significant digits will be printed just like you stored it.
But you would no longer be round-trip safe when the number is the result of a calculation. This is important when you do exact comparisons between floats (eg. to check if data has changed).
So one idea I had was to try printing the float with 6 digits, then scanning it and seeing if it resulted in the same binary representation. If not, try using 7 digits, and so on, up to 9 digits. Then I would have the shortest decimal representation of a float.
This is my algorithm:
int out_length;
char buffer[32];
for (int prec = 6; prec<=9; prec++) {
out_length = sprintf(buffer, "%.*g", prec, floatValue);
if (prec == 9) {
break;
}
float checked_number;
sscanf(buffer, "%g", &checked_number);
if (checked_number == floatValue) {
break;
}
}
I wonder if there is a more efficient way to determine that shortest representation rather than running printf/scanf in a loop?