0

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,");
}
scrowler
  • 24,273
  • 9
  • 60
  • 92
ledesma
  • 248
  • 1
  • 7
  • 18

2 Answers2

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, ",");

Demo

Cilan
  • 13,101
  • 3
  • 34
  • 51
  • but its not formatting as it should... R$ 1.234,00 – ledesma Feb 25 '14 at 01:48
  • @GilbertoGonçalvesMachado What is the `,00`? When should it occur? I don't know much about brazilian currency formatting – Cilan Feb 25 '14 at 01:50
  • i see.. that fixed this problem.. but now i have the other problem that is not formatting the numbers.. – ledesma Feb 25 '14 at 01:52
  • @GilbertoGonçalvesMachado Please explain what you mean by `formatting the numbers..` – Cilan Feb 25 '14 at 01:52
  • ,00 is the cents.. the format is: R$ 1,23 .. R$ 12,34 .. R$ 1.234,56 ... R$ 123.456,78 – ledesma Feb 25 '14 at 01:54
  • when i put format2(number).. its not giving me in the right format – ledesma Feb 25 '14 at 01:54
  • if i put format2(12345) its giving me 12345.00 – ledesma Feb 25 '14 at 01:55
  • @GilbertoGonçalvesMachado I'll try to help, I don't know much about regex... – Cilan Feb 25 '14 at 01:56
  • http://stackoverflow.com/questions/10300930/regex-to-validate-brazilian-money-using-javascript i got the regex sentence from this question.. they said it should work.. but i couldnt see how.. – ledesma Feb 25 '14 at 01:59
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48317/discussion-between-the-wobbuffet-and-gilberto-goncalves-machado) – Cilan Feb 25 '14 at 02:00
0

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
RobG
  • 142,382
  • 31
  • 172
  • 209