scurker / currency.js

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

Issue with precision #394

Closed spencermefford closed 2 years ago

spencermefford commented 2 years ago

Hello. I don't see the precision being applied for me like it is in the examples. Here is a Sandbox:

https://codesandbox.io/s/keen-currying-kb4gws?file=/src/index.js

These are the results I'm seeing:

// Expect: 1.00
currency(1).value
// --> 1

// Expect: 12.50
currency(12.5).value
// --> 12.5

// Expect: 12.50
currency(1250, { fromCents: true }).value
// --> 12.5

These don't align with the examples in the documentation. I've also verified that precision is set to 2 in my console logs.

Any help would be appreciated. Thanks!

Screen Shot 2022-06-15 at 4 28 46 PM
scurker commented 2 years ago

In order to display the full decimal precision you have to convert it to a string, javascript by default doesn't assign any kind of decimal precision to primitive numerical values. currency.js typically depends on type coercion in order to get the right value:

const value = currency(123.40)
console.log(value.toString()) // "123.40"
console.log(value.format())   // "$123.40"
console.log(value.value)      // 123.4
console.log(value.intValue)   // 12340
console.log(value)            
// -> [Object] (this will be the currency.js object itself with all its methods/properties

So if you were to do something like document.getElementById('#input').value = currency(value) it would use the toString method to always display the full decimal precision.

I can certainly see how the documentation can be misleading, so I'm definitely open to improvements to make this more clear.

spencermefford commented 2 years ago

Yep, that now makes a lot of sense. Thanks for the clarification!