currency.js icon indicating copy to clipboard operation
currency.js copied to clipboard

Division seems to be rounding

Open mika76 opened this issue 5 years ago • 4 comments
trafficstars

currency(12345.67).divide(10)

results in e {intValue: 123457, value: 1234.57, s: {…}, p: 100}

it should be 1234.56

mika76 avatar Sep 19 '20 15:09 mika76

By default the precision is 2 so you need to set to the precision you want first, for example 4.

var temp = currency(12345.67, {precision: 4}).divide(10) // Output: 1234.567

// truncate to 2 decimal places, by multiply 100, truncate then divide 100
var result = currency(Math.trunc(temp.multiply(100).value)).divide(100) // Output: 1234.56

let me know if there is better way to do it.

tanchekwei avatar Sep 30 '20 06:09 tanchekwei

Thanks @tanchekwei but maybe the inner divide function should do this automatically - isn't the point of this library; to get around javascript oddities?

mika76 avatar Sep 30 '20 06:09 mika76

😂 I also not sure, as I know this library is mainly to solve floating point issue and still round up. Hopefully they could add a option to let us set need to round up or truncate value.

tanchekwei avatar Sep 30 '20 06:09 tanchekwei

This isn't a floating point issue and is currently working as intended.

12345.67 / 10 is 1234.567. currency.js has to decide how to handle rounding in instances in which there is extra precision so it follows the round half up method. If you actually need to split the amount equally so there's no loss of money, .distribute() will replace any remaining cents onto the first sets of values:

currency(12345.67).distribute(10); // => [123.46, 123.46, 123.46, 123.46, 123.46, 123.46, 123.46, 123.45, 123.45, 123.45]

scurker avatar Sep 30 '20 12:09 scurker