It's OK To Use Floating Point for Money
33 points by technomancy
33 points by technomancy
I once worked as a contractor and was paid by the hour. I had my own hour tracker and also had to put the same information into a third party system they used. I spent quite a bit of time trying to figure out the discrepancy between mine and theirs once. There just was a difference of a few minutes I couldn't explain; theirs didn't add up properly, mine did. I'm convinced that was because they stored time as a floating point number. And in this case, time was money.
This doesn’t seem likely. Even if they were storing everything as seconds since 00:00 1 January 1 AD a float 64 would still have ample precision. You’d need to pick a pretty weird basis and precision to get fp errors in the minute range.
Now, a database field with fixed precision and storing the time in hours? That I could easily believe.
Unix time as float 32 seems like it's in the right order of magnitude:
// time-error.c
#include <stdio.h>
#include <time.h>
int main(void)
{
float f = time(NULL);
float g = f + 120;
double h = ((double) f) + 120;
printf("%f %f %f", g, h, g - h);
}
On my system just now:
$ make time-error
cc time-error.c -o time-error
$ ./time-error
1777220992.000000 1777220984.000000 8.000000
EDIT: The addition isn't even really needed, compounding differences by repeated rounding to 32-bit float could definitely introduce rounding errors on the order of minutes.
You're right that a f64 can accommodate a lot.
Storing time as seconds would be a sane thing to do, so it's quite likely they were storing as fractions of hours. I did get rounding errors in the minute range. Would I get rounding errors on a decimal field, though? Round to one tenth of an hour?
A few of my colleagues track their hours with Excel, and have run into some weird issues there regarding rounding and storing numbers in hours. I wouldn't be surprised if there's some Excel shenanigans going on in the background.
the author confirmed on its mastodon that this was inspired from this article previously on lobste.rs