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?
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.
You can do it like this: printf("%. 6f", myFloat); 6 represents the number of digits after the decimal separator.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With