Home > Software engineering >  How to write a float number to a string, exactly how it is stored in a variable?
How to write a float number to a string, exactly how it is stored in a variable?

Time:07-26

I have a variable that stores a float number. I don't know its precision after floating point. And I need to write it to a string. To do this with sprintf(), I need to know the accuracy.

float a = 3.45; // may change (3.456 , 3.4567 , 3.4 ...)
char result[10];
sprintf(result, "%f", a); // 
printf("%s", result); // result = "3.450000" but i need "3.45"

Help! How can I find out the precision of a number stored in a variable? Or tell me another way how to write a float to a string?

CodePudding user response:

double x = 3.141598256;
for( int i = 0; i < 7; i   )
    printf( "%.*f\n", i, x );

CodePudding user response:

Floating point values are commonly stored as binary values, but we humans love to read them decimal. Unfortunately there is rarely an exact mapping of the fractional part ("after floating point").

To learn more, please read for example this Wikipedia page about floating point numbers.

For example, decimal 0.1 cannot be expressed in binary within limited space, since its expansion does not terminate. 0.1 = 1/10 = 1/16 1/32 1/256 ... Cited from said Wikipedia page:

Whether or not a rational number has a terminating expansion depends on the base. For example, in base-10 the number 1/2 has a terminating expansion (0.5) while the number 1/3 does not (0.333...). In base-2 only rationals with denominators that are powers of 2 (such as 1/2 or 3/16) are terminating.

Bottom line: You cannot know the number of digits after the decimal point. Instead limit the number to a reasonable value, which depends on the value's size and your requirements.

  • Related