Skip to content

Instantly share code, notes, and snippets.

@belchior
Last active December 14, 2016 14:30
Show Gist options
  • Save belchior/c53824ba9c1346ced8c5fd5376d61448 to your computer and use it in GitHub Desktop.
Save belchior/c53824ba9c1346ced8c5fd5376d61448 to your computer and use it in GitHub Desktop.
Convert Number and String with number to brazilian currency
function brazilianCurrency(money, decimalEmbeded) {
var decimalPart;
if (decimalEmbeded) { // example R$72,35 is 7235
money = String(money);
money = 'R$ ' + Number(money.slice(0, -2)).toLocaleString().replace(/,/g, '.') + ',' + money.slice(-2);
} else {
money = 'R$ ' + Number(money).toLocaleString().replace(/,/g, ';').replace(/\./g, ',').replace(/;/g, '.');
if (money.search(',') >= 0) {
decimalPart = money.split(',').pop();
decimalPart = decimalPart.length === 1 ? decimalPart + '0' : decimalPart;
money = money.split(',').shift() + ',' + decimalPart;
} else {
money = money + ',00';
}
}
return money;
}
@belchior
Copy link
Author

belchior commented Dec 14, 2016

Usage:

brazilianCurrency(1234);
> "R$ 1.234,00"
brazilianCurrency(123.4);
> "R$ 123,40"
brazilianCurrency(12.34);
> "R$ 12,34"
brazilianCurrency(1234, true);
> "R$ 12,34"
brazilianCurrency(12345, true);
> "R$ 123,45"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment