javascript icon indicating copy to clipboard operation
javascript copied to clipboard

[FEATURE REQUEST] formatCurrency() / formatDecimal() / formatPercent()

Open silvioprog opened this issue 6 years ago • 3 comments

Hi.

What do you think about to declare those three functions? Something like:

function formatCurrency(value: number, precision: number = 2): string;

function formatDecimal(value: number, precision: number = 2): string;

function formatPercent(value: number): string;

cheers


Useful naive examples for study:

const number = 1234.56;

console.log("Preço:", number.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }));

// > "Preço: R$ 1.234,56"

console.log("Quantidade:", number.toLocaleString('pt-BR', { style: 'decimal' }));

// > "Quantidade: 1.234,56"

console.log("Desconto:", number.toLocaleString('pt-BR', { style: 'percent' }));

// > "Desconto: 123.456%"

References:

  • https://www.freeformatter.com/brazil-standards-code-snippets.html
  • https://pt.stackoverflow.com/a/186798/14540
  • https://www.w3schools.com/jsref/jsref_tolocalestring_number.asp
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

silvioprog avatar Jul 31 '20 04:07 silvioprog

I think it's a good idea, one useful example is when we're working on React-Native env where we don't have the toLocaleString available.

Additionally, I would like to include another function to reverse the operation, something like unformatCurrency

function unformatCurrency (value = '') {
  return parseInt(value.replace(/\D/g, '') || 0, 10) / 100
}

unformatCurrency('R$ 500,00') // 500
unformatCurrency('R$ 1500,00') // 1500
unformatCurrency('R$ 1500,99') // 1500.99

linconkusunoki avatar Aug 24 '20 11:08 linconkusunoki

Nice idea @linconkusunoki ! I would just replace unformatCurrency to parseCurrency.

hyanmandian avatar Aug 24 '20 14:08 hyanmandian

Closed by #132

hyanmandian avatar Aug 25 '20 16:08 hyanmandian