MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.63k stars 743 forks source link

Difference between multipliedBy and dividedBy behaviors #363

Closed matijakevic closed 7 months ago

matijakevic commented 8 months ago

Is there a reason dividedBy operation rounds after applying division, but multipliedBy does not?

Returns a BigNumber whose value is the value of this BigNumber divided by n, rounded according to the current DECIMAL_PLACES and ROUNDING_MODE settings.

It is possible to get big decimal which doesn't respect set DECIMAL_PLACES value after multiplying.

For example (with DECIMAL_PLACES = 2 and ROUNDING_MODE = ROUND_HALF_UP):

Expected: 46.45 12.57 = 583.88 Actual: 46.45 12.57 = 583.8765

This results in adding .dividedBy(1) after every multipliedBy operation to get correct rounding.

MikeMcl commented 8 months ago

The precision of division needs to be limited because the result of dividing two values often has a non-terminating decimal expansion. That is not the case with multiplication.

Use .decimalPlaces(2) rather than .dividedBy(1) to round the result of multipliedBy to two decimal places using the current ROUNDING_MODE.

matijakevic commented 8 months ago

Thank you for your answer, I understand.

Do you think it would be a good addition to this library to allow some sort of flag which will enable automatic rounding after every operation which might create a number with more than specified decimal places. Something like AUTO_ROUND or similar?

This would be useful for some monetary purposes where the amount needs to be rounded after every operation (I guess multiplication might be the only one next to division and other ones which 'creates' more decimal places).