Search code examples
javarounding-error

Math.pi vs Double and rounding via printf in java


I feel like I'm missing something here, but I'm not entirely certain what and I'm relatively new so I'm having trouble searching for exactly what may be causing it.

java snippet follows:

double testDoublePi = 3.145926
System.out.printf("This one rounds: %.2f\tBut this does not: %.2f", testDoublePi, Math.PI );

"This one rounds: 3.15 But this does not: 3.14"

I expected both to be checking the thousandths digit and rounding accordingly, but that's apparently not the case.

I have a sneaking suspicion it has something to do with testDoublePi being finite vs Math.PI, but I'm not sure. I don't have a particular practical application that would require PI to be rounded offhand, but I figure it'd be important to know what's going on before I get myself in trouble and frustrated later.


Solution

  • What happens is that Pi is not 3.145926.... It is 3.1415926.... They are different:

    3.145926  -> 3.15
    3.1415926 -> 3.14
        ^