Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 757
Malic Of Sdom Avatar asked Jun 09 '14 13:06

Malic Of Sdom


People also ask

Does printf truncate or round?

You have to use external commands because there is no built-in rounding feature in printf(1) , and the POSIX shell doesn't have built-in floating-point arithmetic. To round to the nearest decimal digit, you add 0.5 and truncate.

How do I print floating point numbers?

You can do it like this: printf("%. 6f", myFloat); 6 represents the number of digits after the decimal separator.

Does float round off in C?

round( ) function in C returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from ”. 1 to . 5″, it returns integer value less than the argument.

What is used for printing the decimal floating point values?

Use power-of-ten exponential notation, like 2.3e+05, to print the number. The precision specifies the number of decimal places to display in the mantissa, and usually defaults to 6. Use either the " f " or the " e " format, depending on the size of the number to be printed.


2 Answers

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.

like image 144
Yu Hao Avatar answered Sep 22 '22 18:09

Yu Hao


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.

like image 42
Pascal Cuoq Avatar answered Sep 23 '22 18:09

Pascal Cuoq