I'm trying to format a number as brazilian currency, but I'm not sure what's going wrong.
function format2(n, currency) {
return currency + " " + n.toFixed(2).replace(^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
}
I'm trying to format a number as brazilian currency, but I'm not sure what's going wrong.
function format2(n, currency) {
return currency + " " + n.toFixed(2).replace(^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
}
Taken from the comments: “but its giving me a syntax error..”
You're missing a slash to define a regex literal. Change your return statement to
return currency + " " + n.toFixed(2).replace(/^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
^ Teda, the magic opening slash!
Btw, your regex is too complex IMO and doesn't format correctly. I would just do /\./g
to get the matching periods, so your replace statement looks like .replace(/\./g, ",");
I don't know why you're so keen to use a regular expression for this. The following loop solution should be fine and offers a more general solution:
function formatNumber(num, places, thou, point) {
var result = [];
num = Number(num).toFixed(places).split('.');
var m = num[0];
for (var s=m.length%3, i=s?0:1, iLen=m.length/3|0; i<=iLen; i++) {
result.push(m.substr(i? (i-1)*3+s : 0, i? 3 : s));
}
return result.join(thou) + point + num[1];
}
console.log('R$ ' + formatNumber(12345678.155, 2, '.', ',')); // R$ 12.345.678,16
console.log('R$ ' + formatNumber(12.155, 2, '.', ',')); // R$ 12,16