c - How do printf and scanf handle floating point precision formats? -


consider following snippet of code:

float val1 = 214.20; double val2 = 214.20;  printf("float : %f, %4.6f, %4.2f \n", val1, val1, val1); printf("double: %f, %4.6f, %4.2f \n", val2, val2, val2); 

which outputs:

float : 214.199997,  214.199997, 214.20 | <- correct value wanted  double: 214.200000,  214.200000, 214.20 | 

i understand 214.20 has infinite binary representation. first 2 elements of first line have approximation of intended value, the last 1 seems have no approximation @ all, , led me following question:

how scanf, fscanf, printf, fprintf (etc.) functions treat precision formats?

with no precision provided, printf printed out approximated value, %4.2f gave correct result. can explain me algorithm used these functions handle precision?

the thing is, 214.20 cannot expressed exactly binary representation. few decimal numbers can. approximation stored. when use printf, binary representation turned decimal representation, again cannot expressed , approximated.

as noticed, can give precision printf tell how round decimal approximation. , if don't give precision precision of 6 assumed (see man page details).

if use %.40f float , %.40lf double in example above, these results:

214.1999969482421875000000000000000000000000 214.1999999999999886313162278383970260620117 

they different because double, there more bits better approximate 214.20. can see, still odd when represented in decimal.

i recommend read wikipedia article on floating point numbers more insights how floating point numbers work. excellent read what every computer scientist should know floating-point arithmetic


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -