Article 6EQ6Q CodeSOD: Rounding Currency

CodeSOD: Rounding Currency

by
Remy Porter
from The Daily WTF on (#6EQ6Q)

Moz works for a company that needs to handle financial transactions. They use Delphi, which has a handy-dandy fixed precision Currency type, which should make this easy.

Of course, someone opted to do most of the math in double precision floating points anyway. Which lead to this function:

function XWholeCents(dValue: double): Currency;var dAdditionalAmount: double; // used to stop a rounding problem with Delphibegin try dAdditionalAmount := 0.0001; if (dValue < 0) then begin dAdditionalAmount := -1 * dAdditionalAmount; end; Result := XStrToCurr(FormatCurr('#######0.00', dValue + dAdditionalAmount)); except Result := 0.00; end;end;

The core of this method is a pretty traditional "convert a number to a string, then parse the string back into a number" bit of WTFery. The "secret sauce" on this one is its attempt to "stop a rounding problem with Delphi". They shift the number one ten-thousandth of a cent away from zero, then format it down to two decimal places, which rounds off. Then they can convert it back to a Currency type.

If they had been using Currency the whole time, none of this would be necessary.

In any case, if you're wondering what is going on with that rounding, I'll let Moz explain:

The rounding? Lets just say that my current task is to discover why the way we round totals is so often wrong.

otter-icon.png [Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments