js-money
js-money copied to clipboard
Getting TypeError: Amount must be an integer on test value `315.15`
The code snippet below throws Getting TypeError: Amount must be an integer
import MoneyLib = require('js-money');
MoneyLib.fromDecimal(300.15, 'PHP');
This line appears to be causing the problem: https://github.com/davidkalosi/js-money/blob/10a4870fa8fd47eb27d0ac794ad4dfd24150277a/lib/money.js#L119
The result produced is 30014.999999999996
which is not the integer that's expected.
Can also reproduce with new Money(34.98, currency)
. Will occur in any value in which n * 100
cannot be precisely held by JS float representation.
bad solution: next line, resultAmount = Math.ceil(resultAmount);
good solution: do math with an appropriately precise decimal library: https://github.com/MikeMcl/decimal.js/
Just give your money in cents/pennies eg:
import MoneyLib = require('js-money');
MoneyLib.fromDecimal(30015, 'PHP');
The Money.fromDecimal function allows you to pass a third parameter of "rounder" which should be one of Math.ceil, Math.floor, or Math.round. You can then create your Money object without error like so:
Money.fromDecimal(300.15, Money.PHP, Math.round);
@mothman103182 Passing a "rounder" function just burdens the application using it. You just remove the issue in the library and let application handles it. Why not use big decimal instead for precise numeric operations?