scurker / currency.js

A javascript library for handling currencies
https://currency.js.org
MIT License
3.15k stars 142 forks source link

Percentage #466

Closed rwieruch closed 7 months ago

rwieruch commented 7 months ago

Hi there.

I try to calculate the percentage like this:

const result = currency(price).divide(100).multiply(percentage).value;

Now I have the following variables:

const price = 18.50;
const percentage = 3;

The interesting part is that I would have assumed the result to be 0,56, because when I use my calculator it is 0,555. However, since currency is rounding in between to precision of 2 by default, I get 0,57 as result.

So there is nothing wrong with the library, just something to be aware of when calculating percentages I guess.

The solution, I think, would be either:

const result = currency(price).divide(100, { precision: 3 }).multiply(percentage).value;

or maybe better say that the rounding should only happen at the end:

const result = currency(price / 100 * percentage).value;

The former may be wrong for certain edge cases as well, because of the intermediate rounding where we need more than precision of 3.

Just wanted to leave this here for reference. Feel free to close the issue.