The Joys of Rounding

21 Nov 2007

Quick! What is the output of this:

#include 
int main() {
    printf("%.1f %1.f %.1f", 1.5, 2.5, 3.5);
    return 0;
}

It turns out Unix based systems (at least on linux glibc and bsd/mac systems), use Round-To-Even rules (this is good):

2 2 3

But on Windows, it's Round-Half-Up (this is bad)

2 3 4

For truly portable programs, you'll need to use a 3rd party implementation of printf (see APR, NSPR or GLIB)

Unfortunately I can't test this for C++ and it's formatting styles and see if there is a difference between Unix and Microsoft systems.