Why printf round floating point numbers?

I am trying to print some floating point numbers using printf. For example:

int main()
{
    printf("%.1f",76.75); 
    return 0;
}

THE OUTPUT: 76.8

And I have some questions about the result.

First of all, why didn't it print 76.7?

Second, how did it round the number?


Solution 1:

C99 §7.19.6.1 The fprintf function

f,F

A double argument representing a floating-point number is converted to decimal notation in the style [−]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the # flag is not specified, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.

Solution 2:

In addition to existing answers, note that many C compilers try to follow IEEE 754 for floating-point matters. IEEE 754 recommends rounding according to the current rounding mode for conversions from binary floating-point to decimal. The default rounding mode is “round to nearest and ties to even”. Some compilation platforms do not take the rounding mode into account and always round according to the default nearest-even mode in conversions from floating-point to decimal.

Since 76.75 represents the number 7675/100 exactly, it is precisely halfway between 76.7 and 76.8. The latter number is considered the “even” one when applying “round to nearest-even”. This is probably why your compilation platform chose to generate this decimal representation as the conversion to decimal of the floating-point number 76.75.

Solution 3:

First of all, why he didn't print 76.7?

Because the language specification says that the low-order digit will be rounded.

how he rounded the number? (some code would help)

This differs implementation-by-implementation. According to the documentation,

The low-order digit shall be rounded in an implementation-defined manner (emphasis added).