0

I need to convert values like 100000 ​​to the Brazilian currency format (Real) 1.000,00 and I am using javascript.

That would be in this pattern.

0,00
1,00
10,00
100,00
1.000,00

I managed to create the decimals using this expression.

if (v.indexOf('.') === -1) {
    v = v.replace(/([\d]+)/, '$1,00');
  }

Now I'm having trouble separating when I have values ​​above 1000,00 which would be 1.000,00.

I'm using the keyup that calls the function and writes the value in another field (Total) and this function that does all the work of converting the number to "Reais"

I did this function

String.prototype.formatMoney = function () {
  let v = this;
   
  if (v.indexOf('.') === -1) {
    v = v.replace(/([\d]+)/, '$1,00');
  }

  v = v.replace(/([\d]+)\.([\d]{1})$/, '$1,$20');
  v = v.replace(/([\d]+)\.([\d]{2})$/, '$1,$2');
  console.log(v);

  return v;
};

My regex knowledge is weak, can somebody help me please?

Dani Drummond
  • 44
  • 1
  • 6
  • 1
    You don't need to do all that. Just use [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) – Randy Casburn Feb 21 '21 at 17:27
  • Thanks Andrew and Randy I will read the articles and any questions I come back to here – Dani Drummond Feb 21 '21 at 18:04

0 Answers0