# The foxNET series: Rounding

2007-02Feb-10

In the past year I've received an increasing amount of incorrect invoices. I'm not talking about fake invoices, virus attachments or subscription reminders. The invoices I'm talking about were real invoices, except that the amount of VAT was off by one cent, sometimes up, sometimes down. What does this have to do with VFP or .NET?

Rounding away from zero means that positive numbers are rounded up (2.5 becomes 3) and negative numbers are rounded down (-2.5 becomes -3). When you round to even, you round up or down depending on the digit just before 5. If the digit is even, you drop the five. Otherwise you round up to the next even digit. So 1.5 is rounded up to 2, but 2.5 is rounded down to 2. Visual FoxPro rounds away from zero:

The .NET framework, on the other hand, defaults to round to even:

Both lines print 2. If you want to get the same results as in Visual FoxPro, you have to specify the rounding algorithm as a second parameter:

Now you get the same results as in Visual FoxPro. For the US this change has probably increased the amount of correct invoices, since rounding to even is what accountants use there. In Germany, though, accountants use the "round away from zero" rule. A surprisingly high number of developers don't seem to be aware of the difference. Hence, as accounting software is ported over to .NET here, the number of rounding errors increases.

? Round(1.5,0) && prints 2

? Round(2.5,0) && prints 3

The .NET framework, on the other hand, defaults to round to even:

Console.WriteLine("1.5 rounded is {0}", Math.Round(1.5));

Console.WriteLine("2.5 rounded is {0}", Math.Round(2.5));

Both lines print 2. If you want to get the same results as in Visual FoxPro, you have to specify the rounding algorithm as a second parameter:

Console.WriteLine("1.5 rounded is {0}",

Math.Round(1.5, MidpointRounding.AwayFromZero));

Console.WriteLine("2.5 rounded is {0}",

Math.Round(2.5, MidpointRounding.AwayFromZero));

Now you get the same results as in Visual FoxPro. For the US this change has probably increased the amount of correct invoices, since rounding to even is what accountants use there. In Germany, though, accountants use the "round away from zero" rule. A surprisingly high number of developers don't seem to be aware of the difference. Hence, as accounting software is ported over to .NET here, the number of rounding errors increases.