openexchangerates / accounting.js

A lightweight JavaScript library for number, money and currency formatting - fully localisable, zero dependencies.
http://openexchangerates.github.io/accounting.js
MIT License
4.95k stars 532 forks source link

Rounding #1

Closed spinron closed 13 years ago

spinron commented 13 years ago

The rounding is inconsistent. 0.615 gets rounded to 0.61.

Suggestion: You also might want to specify the rounding method: Normal mathematical rounding (round 0.5 away from 0) and bankers' rounding (round 0.5 to nearest even number) which is more often used in accounting. You might even go crazy and ask for the rounding radix...

wjcrowcroft commented 13 years ago

Good call, thanks for letting me know - if you have any ideas for a fix, please fork the repo and make some commits and I'll be happy to merge them back in if it works!

wjcrowcroft commented 13 years ago

The rounding issue (0.615 rounds to 0.61 when the precision is 2 decimal places) is a language-level implementation issue caused by the way binary values are represented as floating point numbers - see http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem for more info, and there's a whole load written about it.

edit I've added a toFixed method to the library that treats floats more like decimals and less like binary, hopefully that'll fix it.

Gotta review it tomorrow when I wake up and see if it still makes sense, then will push it in.

wjcrowcroft commented 13 years ago

This is fixed in the latest push, v0.1.1, with a new toFixed() method that is used in formatNumber():

(0.615).toFixed(2); // "0.61"
accounting.toFixed(0.615, 2); // "0.62"
jnthnhrrsn commented 11 years ago

It looks like 100.999 rounds to 100.00 instead of 101.00. Is that an associated issue?