Reputation: 61
Could you please explain this code:
printf("Value1: %0.1f \n", (float)124/100); // = 1.2
printf("Value1: %0.1f \n", (float)125/100); // = 1.2
printf("Value1: %0.1f \n", (float)126/100); // = 1.3
printf("\n");
printf("Value2: %0.1f \n", (float)134/100); // = 1.3
printf("Value2: %0.1f \n", (float)135/100); // = 1.4
printf("Value2: %0.1f \n", (float)136/100); // = 1.4
Why is the number 125 rounding down to 1.2 and 135 rounding up to 1.4? For example, it also happens with the numbers 105, 115, 125, 155, 165.
Upvotes: 4
Views: 411
Reputation: 223842
The C standard does not fully specify either the float
format or how rounding is performed. Most C implementations today use the IEEE-754 binary32 format for float
. In this format:
If you change %0.1f
in the printf
calls to %.99g
, your C implementation will likely show you those values.
The most common rounding rule used is to round to the nearest representable value and, in case there is a tie, to round to the tied value with an even low digit. This is the rule almost always used in arithmetic operations (notably addition, subtraction, multiplication, and division), so your C implementation likely uses it when calculating (float)124/100
and so on.
That rule is also often used when converting numbers from the internal binary float
format to numerals in character strings, as with printf
. (The rule is used a little less often in this case because some conversion software is not written to use the precision or calculations necessary to always produce correct results according to this rule.) The output you observe is consistent with use of this rule:
Upvotes: 4