Question : Rounding question

I am trying to round using the AwayFromZero option.  Generally this is working fine.  However, there seems to be one instance causing a problem.  Here are three tests that I ran:

    MsgBox(Math.Round(0.291575, 5, MidpointRounding.AwayFromZero).ToString)  '--> Returns .29157
    MsgBox(Math.Round(0.391575, 5, MidpointRounding.AwayFromZero).ToString)  '--> Returns .39158
    MsgBox(Math.Round(0.491575, 5, MidpointRounding.AwayFromZero).ToString)  '--> Returns .49158

Why is the first one rounded to a final digit of 7 and the others to a final digit of 8?  I would expect that all three round to a final digit of 8.  What am I missing here?

Answer : Rounding question

The rounding you apply will round up when the digit you want to round is a 5. Otherwise it will round down. This may sound odd, but your first number ends up having a "4" at fifth decimal place. The reason is in the IEEE 754 standardized method of mapping decimal floating points to a binary representation: there's limited room for precision in 32 bits.

To see what I mean, try the following in the Immediate window:

?0.291575
0.29157499999999997

As you can see, the double "0.291575" is actually, internally "0.291574....". Hence the rounding down.
Random Solutions  
 
programming4us programming4us