printf rounding behavior for doubles

16,056

It's "round half to even" or "Banker's rounding". The last digit of the rounded representation is chosen to be even if the number is exactly half way between the two.

http://linuxgazette.net/144/misc/lg/a_question_of_rounding_in_issue_143.html:
"For the GNU C library, the rounding rule used by printf() is "bankers rounding" or "round to even". This is more correct than some other C libraries, as the C99 specification says that conversion to decimal should use the currently selected IEEE rounding mode (default bankers rounding)."

Share:
16,056
user443854
Author by

user443854

Updated on June 04, 2022

Comments

  • user443854
    user443854 almost 2 years

    Can someone explain this behavior? I am well aware of machine-level representation of floating point numbers. This seems to be related to printf and its formats. Both numbers are represented exactly by floating-point notation (check: multiplying by 64 gives an integer).

    #include <stdio.h>
    #include <iostream>
    using namespace std;
    
    int main() {
      double x1=108.765625;
      printf("%34.30f\n", x1);
      printf("%9.5f\n", x1);
      printf("%34.30f\n", x1*64);
    
      double x2=108.046875;
      printf("%34.30lf\n", x2);
      printf("%9.5f\n", x2);
      printf("%34.30f\n", x2*64);
    }
    

    Output:

    > 108.765625000000000000000000000000
    > 108.76562
    > 6961.000000000000000000000000000000
    > 108.046875000000000000000000000000
    > 108.04688
    > 6915.000000000000000000000000000000
    

    Note, the first number gets rounded down, and the second one gets rounded up.

  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE about 12 years
    The author of the linked article is incompetent. "Binary and decimal radix do not share the same set of irrational numbers" - that's nonsense. Rationality/irrationality is independent of base.
  • Daniel Fischer
    Daniel Fischer about 12 years
    @R.. Indeed. But the quoted passage of the article is correct, as the author painfully learned in his bug report.
  • Spike0xff
    Spike0xff over 4 years
    The point of the question, I believe, is: what if the source number is exactly halfway between two possible outputs?
  • Antti Haapala -- Слава Україні
    Antti Haapala -- Слава Україні over 3 years
    "not all finite decimal expansions have finite binary expansions"