Why printf (Unix) uses the round half?

Why does printf behave in such an unusual way?

> printf %.0f 2.5
> 2
> printf %.0f 2.51
> 3

Is there an advantage to behavior that compensates for possible misunderstandings (like this one )?

+4
source share
2 answers

This is not strictly round:

> printf '%.0f\n' 2.5
2
> printf '%.0f\n' 3.5
4

This is a rounding form used to combat bias if you round a large number of values; approximately half of them will be rounded, the other half rounded. The rule is rounded if the integer part is even, up if the integer part is odd.


This, however, is only an explanation of the specific rounding scheme, which is not guaranteed for all implementations printf.

+4

POSIX printf:

printf() , . awk printf. bc , . ( printf bc, .) .

: %f ; , , .


, , POSIX printf():

f, F

"[-] ddd.ddd", radix . , 6; , '#' , . , . .

, , "[-] inf" "[-] "; . , NaN, "[-] nan (n- char -sequence)" "[-] nan"; n- char -, . F "INF", "INFINITY" "NAN" "inf", "" "nan" .

0

All Articles