openexchangerates / accounting.js

A lightweight JavaScript library for number, money and currency formatting - fully localisable, zero dependencies.
http://openexchangerates.github.io/accounting.js
MIT License
4.95k stars 528 forks source link

unformat with the decimal specified to deal with decimal for thousands #183

Open pycarlson opened 6 years ago

pycarlson commented 6 years ago

Signed-off-by: Brad Midgley bmidgley@mavenlink.com

formatMoney will fail on currencies that have a dot for the thousands separator.

fixes: https://github.com/openexchangerates/accounting.js/issues/129

thomasjlee commented 6 years ago

After looking into this issue it is apparent that the intended usage of formatMoney does not securely allow for number to be passed as a string. Numbers which use "." as a thousand separator must be wrapped in quotes, since JavaScript will not correctly interpret a number such as 1.234,56. The proposed fix may not be reliable since options to formatMoney can be passed either individually:

formatMoney( number, "R$", 2, ".", ",", "%s %v" ); // 6 arguments

... or, as an object:

formatMoney( number, {
  symbol: "R$",
  precision: 2,
  thousand: ".",
  decimal: ",",
  format: "%s %v"
} ); // 2 arguments

I believe the best work around for currencies which use ".' as a thousand separator is this two step process:

// Manually unformat the number passed as a string:
var number = accounting.unformat( "1.234,56", "," ); // number => 1234.56

// Pass the unformatted number to formatMoney with appropriate options:
accounting.formatMoney(number, {
  symbol: "R$",
  thousand: ".",
  decimal: ",",
  format: "%s %v"
}); // "R$ 1.234,56"