Skip to content

Instantly share code, notes, and snippets.

@dirceu-jr
Created March 25, 2019 18:02
Show Gist options
  • Save dirceu-jr/a392f66e68348f48c0144b4f90857113 to your computer and use it in GitHub Desktop.
Save dirceu-jr/a392f66e68348f48c0144b4f90857113 to your computer and use it in GitHub Desktop.
Formatar Dinheiro LATAM - JavaScript
var currency_map = {
'ARS': {abrv: '$ ', cents: 2, mi: '.', cent: ','},
'MXN': {abrv: '$ ', cents: 2, mi: ',', cent: '.'},
'BRL': {abrv: 'R$ ', cents: 2, mi: '.', cent: ','},
'CLP': {abrv: '$ ', cents: 3, mi: '.', cent: '.'},
'COP': {abrv: '$ ', cents: 2, mi: '.', cent: ','},
'PEN': {abrv: 'S/. ', cents: 2, mi: '.', cent: ','},
'VEF': {abrv: 'Bs.F. ', cents: 2, mi: '.', cent: ','}
}
function formatMoney(n, currency){
var
currency = currency_map[currency],
c = currency.cents,
d = currency.cent,
t = currency.mi;
var c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
if (n > 0) {
return "<em>" + currency.abrv + "</em>" + s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
} else {
return "Consulte";
}
}
// usage
formatMoney(5, "BRL");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment