scurker / currency.js

A javascript library for handling currencies

Home Page:https://currency.js.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

incorrect intValue

csechuan opened this issue · comments

const result = currency(1002, { increment: 0.05, fromCents: true }
// result = 10.00
// result.intValue = 1002

Shouldn't the result.intValue is 1000?

How do I get the result of the rounding in int value correctly?

commented

This one is a bit tricky, the intValue is used internally to keep track of the "true" value, the increment property only sets the the value when its converted to a string. Otherwise when doing a series of operations the value would drift because it would be setting the increment value at each step.

Here's how it's currently documented:

var currencyRounding = value => currency(value, { increment: .05 });
currencyRounding(1.09); // => { intValue: 109, value: 1.09 }
currencyRounding(1.09).format(); // => "1.10"
currencyRounding(1.06); // => { intValue: 106, value: 1.06 }
currencyRounding(1.06).format(); // => "1.05"

While not ideal, one way to work around this is to pass the resulting value back into another currency value:

var currencyRounding = currency(1.03, { increment: .05 });
var currencyValue = currency(currencyRounding.format())
currencyValue.intValue; // 105

I could see something like this changing, but it would need a non-breaking proposal.

i see. at least this work. thanks!!