javascript
javascript copied to clipboard
[FEATURE REQUEST] formatCurrency() / formatDecimal() / formatPercent()
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
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
Nice idea @linconkusunoki ! I would just replace unformatCurrency to parseCurrency.
Closed by #132