133 points · by fagnerbrack · 8y ago · 108 comments
Not sure what the back office did, but I doubt it was all done in arbitrary position arithmetic.
Note that if an accountant says things need to be accurate down to the penny, that's probably an exaggeration [1]. Financial statements are typically rounded to the thousands, e.g. Intel's are rounded to million [2].
The IRS also lets you round off dollars [3].
I agree though that if you're building a large complex system with many coders, and either 1) nobody has a full view of the calculation and can do the numerical analysis or 2) there's a high chance that at some point in the future you need penny-accurate bookkeeping, then it's safer to use a very wide int or float type.
Of course, there's also the case where the accountant or auditor doesn't actually need penny precision, but it's easier to just tell the coder 'just in case'.
[1] https://www.accountingtools.com/articles/2017/5/14/the-mater...
[2] https://s21.q4cdn.com/600692695/files/doc_financials/2017/an...
[3] https://taxmap.irs.gov/taxmap/pub17/p17-006.htm#TXMP5d034bfb
At a minimum, you look like a rinky dink operation that doesn't know how to add dollars and cents. On the other end of the spectrum, some people will likely accuse you of theft, and not nicely.
Do not fall under the assumption that the amount you mis-bill will inform how upset the people are that contact you. You will likely be the easy and obvious scapegoat for all their recent annoyances. For example, imagine all the people upset at their AT&T, Comcast or Verizon bill, who now have an easy and obvious thing to point at as an example of over billing. Have fun with those transferred emotions...
Note that the article's advice is to use their own library, but the library just uses JS floats as ints and a separate precision arg:
https://github.com/sarahdayan/dinero.js/blob/master/src/dine...
This doesn't give you any more precision than using floats directly, just a wider 'mantissa' range.
Some background: funds can handle fractional quotes and each fund can have its own rounding rules, funds mixes can handle fractional percentages, when money enters or leaves the system it gets rounded to cents because you can't move fraction of cents (unless digital)
So, you get issues even using arbitrary precision math.
Operation order matters. Rounding impacts everywhere so you need to be consistent across the business logic, reversing an operation need to have rounding applied in a specific order to result in the final date to match the initial.
Order is also important when splitting money, because the last share gets all the leftover cents that come from rounding the previous shares split so that the total gets allocated fully. I.e. moving the last 1$ from one fund mix to another mix that has 3 equally divided fund is going to round as .33 movement toward each, but you can't just leave that cent on the previous fund mix and you can't just drop it going nobody notices, so one of them gets .34
maybe this is not a technical issue, maybe its a subculture interaction issue that involves a lot of technical details.
i dont think its easy to 'understand' unless one group spends time with another, and i dont mean half an hour meeting, i mean like, shadowing someone for a week.
Having access to rational numbers is great and there are times they are incredibly useful, but I don't think it's a good default.
This means that the denominator won't get arbitrarily large.
For serious uses of rationals you need to have control over when the top and bottom are divided by the GCD. For currency you want to keep the denominator at 100. 50/100 wants to remain as that and not get simplified to 1/2.
The link to the scheme documentation that goes over this is quite good.
Honestly, most all older manuals and documents that were not related to systems programming seem to cover numeric programming decently enough. I get the impression that languages used to worry more about that sort of thing, but then the truly heavy lifting of numeric programming moved into the specialized domains of Matlab and friends, and then programmers slowly unlearned most of what was learned regarding numbers.
Yet, there’s no consensus around how to programmatically handle monetary values.
I wonder if the average person would find this frightening.
In the Java world, there's JSR-354: https://jcp.org/en/jsr/detail?id=354
Cobol has handled money well for decades.
.NET has Decimal, which should handle money correctly as long as you're working with values less than 79.2 octillion.
In my part of the world, at least, big banks tend to be mostly Java and Cobol on the back end. You'll definitely see Node, Go, and others being used for various tasks throughout the company, but when it comes to keeping track of money and moving it around, it's primarily Java and Cobol doing the heavy lifting.
That's what I've heard from other developers, anyway. I haven't worked at a bank myself.
Python uses it: https://docs.python.org/3.5/library/decimal.html
Just because JS is stupid doesn't mean other languages are.
This bewilders me. They keep cramming so much new stuff into JS these days - arrow operators, promises, async/await, God knows what, but not ints? I'm not asking for the whole numeric tower of Lisp languages, I can live without rationals and bignums and complex numbers. But a God's own fixed-width integer. You'd think they'd add it in the years since JS started being used for serious things.
As others have noted, if you're doing any kind of math that involves floating point numbers and you will displaying them to a user, you'll almost certainly want something like this.
While it's not specifically a "Money" class it can form an excellent base for one.
IBM has had a solution for a long time: http://speleotrove.com/decimal/
Python uses it: https://docs.python.org/3.5/library/decimal.html
Get a proper decimal library, and then you can devote brain cells to actual problems. The IBM link above includes links to libraries that do it right.
With float64's maximum 'safe' integer at almost ten thousand trillion, I believe this should be enough to compute most commercial transactions securely as long as the amounts base denomination is up to date (eg cents or dollars or megadollars).
The quantization noise mentioned in this article is possible to round off when appropriate.
function round_tail_digits(c){
return Math.round(c*1e15)/1e15
}
function round_at_hundreds(c){
return Math.round(c*100)/100
}This is probably over-engineering.
Currencies that go through hyperinflation typically end up being officially re-denominated many times, there's no 'zero maintenance' path that a library will give you.
$ node
> 0.1 + 0.2 - 0.3
5.551115123125783e-17
Close enough for trivial cases but errors can accumulate.Ruby, Perl5, Python also fail this. Perl6 uses Rat numbers for things like this and doesn't have this problem.
Ruby and Python have arbitrary precision decimal and rational support in the standard library. While there are arguments tobe had over whether using binary floats by default for simple decimal literals is a good choice, that's a different issue than not having any other kind of numbers available by default.
Do the same with a proper decimal datatype, and the same operations give the correct result - pay out 1/3=0.33; pay out 1/3=0.33; the last payment is 1-0.33-0.33 = 0.34 exactly.
The same goes with all kinds of other issues e.g. totalling up tax or discount amounts (calculated as a percentage) where you'll get mismatches if rounding happens at the wrong time, etc.
E.g. ten separate receipts each selling a 0.10 item with a 9% tax or discount will result in each receipt having 0.01 tax or discount; so the proper total in this case is 1.00 sales with 0.10 tax or discount; different than the case if you sell ten such items in a single transaction. If you do all the calculations in floats, you get this wrong.
(1.005).toFixed(2) // Expected rounding to "1.01"
"1.00"2.875.toFixed(2) = "2.88" while 2.675.toFixed(2) = "2.67"
7205759403792794 + 1.1 = 7205759403792795
7205759403792794 + 1.9 = 7205759403792796
for (let n = 0; n < 1; n += .01) { console.log(`n: ${n}, half: ${(n / 2).toFixed(2)}`); }
Dinero({amount: 5000, currency: 'USD'})
.add(Dinero({ amount: 1000, currency: 'EUR'}))
...and then convert that sum to a concrete currency later.This feature request inspired by http://blog.ploeh.dk/2017/10/16/money-monoid/
If you’re keeping these values around in memory for an extended period of time time and you care about rapid changes to exchange rates, then you have a complex domain and the deferred exchanges may or may not be a good fit, but at that point you need larger system design, not a JavaScript library.
Also in my dream money library, division and multiplication would be done with whole number fractions like
new Dinero({amount: 1000, currency: ‘usd’})
.multiply({numerator: 1, denominator: 3 })
which can similarly be deferred to prevent rounding errors in partial calculations.I think generally you 'need to know' immediately.
Source: worked at a bank that implemented pretty much this.
This technique is fantastic for units that don’t change relations though, like mass and length.
> You must provide your own API to retrieve exchange rates.
https://sarahdayan.github.io/dinero.js/module-Dinero.html#~c...
You can implement a correct set of fraction manipulation functions in well under 100 lines of code with a bit of algebra. It seems likely there are several well-tested high-performance fraction libraries for JavaScript. They should be tiny.
Some people in the UK apparently voted to leave the EU so that they could have a blue passport [0], perhaps there are some who also hope we return to imperial measurements and pounds, shillings and pence. I'm quite sure that even in that unlikely event, some programmers will still insist on using floating point numbers for currency.
[0] Although Malta has a blue passport and is in the EU. And the only reason the passports were blue in the first place was to meet an international standardization.
The question is how much of an issue is this really? How often is 4 parts in 10 quadrillion a meaningful error when dealing with money? Especially when most of the time JS is dealing with money it will be presentation.
I spent 13 years maintaining a 2mloc reservation and accounting system that used floats for everything. By the time I got there and understood enough it was simply too late to do anything about it.
Just say no, really; that road leads to madness.
If you need precision; and many do; consider fixnums, rationals or bignums, in order of increasing complexity and flexibility.
This is in general how floating point math works.
The kind of issue do not want to have: issues with money that can go very wrong when calculating discounts, tax percentages, interest or whatever.
The firm I worked at used built in Java libraries and always deferred rounding until the very last possible moment.
Do what COBOL does and use it to verify your monetary library. Your code will agree with the majority of financial institutions.
Ie. if the price is 150.95 I store 15095 in the db and do the calculations with cents, and then divide by 100 when presenting the values.
I have never come across fractional cents, maybe that is an issue in some scenarios (would be interested to know what those are... Even tax percentage calculations are rounded to the cent)
There's a good article on this subject here:
In the contrived example of splitting a value of 999.99 among more than one payment, the correct solution is:
* Determine the next payment based on the current balance.
* Invoice/Apply/Etc that payment
* Repeat until there is a balance of 0 (zero).For the love of God, just don't.
It was interesting. Here are some simple cases to try. One or more of these break most of the seemingly obvious approaches:
1% of $21.50
3% of $21.50
6% of $21.50
10% of $21.15
Here are some examples of obvious looking but wrong approaches. These all return the tax in pennies, so the desired results are 22, 65, 129, and 212. In puts are floats, such as 0.01 for 1% and 21.50 for $21.50. # 1%, 10% wrong
def tax_f1(amt, rate):
tax = round(amt * rate,2)
return round(tax * 100)
# 3%, 10% wrong
def tax_f2(amt, rate):
return round(amt*rate*100)
# 6% wrong
def tax_f3(amt, rate):
return round(amt*rate*100+.5)
Here are two that do work: def tax_f4(amt, rate):
amt = round(amt * 100)
rate = round(rate * 10000)
tax = (amt * rate + 5000)//10000
return tax
def tax_f5(amt, rate):
amt = int(amt * 100 + .5)
rate = int(rate * 10000 + .5)
tax = (amt * rate + 5000)//10000
return tax
If instead of floating point input, you work with numbers already scaled up to integers (scaling the rates by 10^4 and the money by 10^2), this works: def tax(amt, rate):
tax = (amt * rate + 5000)//10000
return tax
The last three approaches, (tax, tax_f5, and tax_f4) also work well in PHP, Perl, and JavaScript.In my code, I attach a suffix to rates and moneys that are scaled this way telling the scale factor, so I might have tax4 and cost2, meaning the tax rate is x10^4 and the cost is x10^2. I was disappointed to find that neither Perl nor Python would let my use Unicode subscript numbers in my variable names. :-(
I also did a series of exhaustive tests where I'd take every string of the form every string of the form digits dot digits with up to N digits after the dot, parse them with the languages most natural string to float converter, multiple that by 10^N and round to an integer, and verify that this was the "right" integer, and also verified that doing a floating point divide of that integer by 10^N and then using the most natural way in the language to turn that to a string with N digits after the dot gave the right result.
The idea here was to convince myself that I would not run into problems at the "convert to integer" or the "convert from integer" part. I did these tests in C, Perl, Python, and JavaScript I think. I'm having trouble finding my code now so I'm not sure if I tested in all of them.
Anyway, I concluded that it was safe. It's only when you start computing in float point that you have to worry.
Finally, in most of what I was doing at the time, I actually didn't ever need to convert back to a floating point format. All I was going to do with the final price, computed from cost + tax, was just display it to the user...and so if I converted to floating point I'd end up just sprintf'ing it (or equivalent) back to a string. All sprintf would really be being used for was to make sure it had the right padding and leading zeros and stuff like that.
So instead of going through floating point, I just did this (JavaScript):
function cents_to_dollars(cents)
{
cents = cents.toString();
while (cents.length < 3)
cents = '0' + cents;
return cents.substr(0,cents.length-2) + '.' + cents.slice(-2);
}
(I assume that if I knew JavaScript I could do something much nicer than that while look for the padding).This is waay overstating the case, it very much depends on whether getting the exact answer down to the penny matters to you.
Worked for a few years at a large investment bank, everything was done in floats because the modeling error of your derivatives pricers would be much larger than the roundoff error, but floats were much more convenient to develop with and faster since you avoided a bunch of casts.
Most of the time people think they need things down to the penny, they actually don't. An accountant does not care if you rounded off a few thousand dollars in your $10bn a year income statement.
A customer does not really care that you paid them $0.33 three times, rather than $0.33 twice and $0.34 on the third transaction (and fixnums don't even solve this 'extra precision' case without a bunch of extra work).
Here's how it would go:
"Why are we losing a couple of thousands of dollars?"
"Well it was easier to just work in floats"
"Pack your shit and get the f--- out of here, now."
We've never done $ math in JS, that just seems like a stupid place to do it. If it's in the browser, you can't trust anything that happens there anyways, as it runs client side, with almost zero security. We happily take $ input via JS on the client, but we just pass it through, and let the server(s) handle the actual math.
I think we're talking past each other a bit.
Financial products pricers themselves only have as much precision as the inputs, which in many cases might only have 3-5 significant figures. Using arbitrary precision math doesn't buy you any more precision than what your inputs have.
Remember that a 64-bit float gives you 52 bits ~ 14 decimal digits of precision, so unless you're doing something that has terrible numerical stability, the error of your model assumptions and inputs will always dominate floating point error. It doesn't matter if your model spits out $XXXXXX.08 or $XXXXXX.15 - both answers are essentially the same.
Just to provide context, we were pricing deals with notional amounts in the billions and PVs up to tens of millions.
Note that we're comfortable doing nuclear bomb simulations or climate models using FP64 floating point calculations, for the same reasons — the error in your model is bigger anyway.
> they would have you fired over the superfluous loss of a dollar
The handling of customer accounts is different at a bank since you're not supposed to be creating or losing money out of thin air—that's the Fed's job.
But that's not what the article claims—it claims that any monetary amount, anywhere, should never use a float, which IMO overstates things from both a business and maths standpoint.
Turns out that the first thing a financial analyst does to compare two implementations of a bond securitization model is to look at the pennies. If those tie out, then you're good. But if your software predicts money off by a dime in a billion dollar model deal, the analyst WILL notice and WILL try to get to the bottom of it.
Yeah, floating point roundoff error seems like it should be immaterial. However it can matter a whole lot.
The founder at the last place I worked at was famously difficult to satisfy because of this. You couldn't even begin to talk about how you were presenting data to him unless you were absolutely sure the numbers in your mockup were correct. He just couldn't see past an "incorrect" value when dealing with faked data ...