Remove mask with javascript

Asked

Viewed 1,995 times

0

I have a form where brings BD and includes in the value of a text field the monetary value and with PHP (number_format) create the mask below for user view:

R$ 12,000,00

<input type="text" id="valorTotal" class="form-control" value="<?php echo number_format($valorTotal,2,',','.'); ?>" onchange="calcular()">

But I’m using Javascript for calculations and this field will be used. How would I remove this mask with Javascript making it look like this:

12000.00

Or without a thousand:

565.00

While doing the calculation and at the time of the presentation in another field the results, get back to with the mask:

<input type="text" name="ValorFinal" id="valorFinal" class="form-control" onchange="calcular()" required="required" readonly>

<script>
.....
document.getElementById('valorFinal').value = parseFloat(Math.abs(valorPP));
...
</script>

2 answers

4


You can use regular expression with "replace":

var value = "R$ 12.000,00";
var clean = value.replace(/[^0-9,]*/g, '').replace(',', '.');
alert(clean);

In the above code, the result will be a string "12000.00" If you need to format the number for a decimal numeric type, for example, do the following:

var value = "R$ 12.000,50";
var clean = parseFloat(value.replace(/[^0-9,]*/g, '').replace(',', '.')).toFixed(2);
alert(clean);

In both cases, the secret is in the expression /[ 0-9,]*/g. where:

  1. /.../g: tells javascript to replace all incidences found (g).
  2. [^0-9,]*: have anything "not numerical" and "not comma removed" (^);
  3. Finally, the second "replace" replaces the comma by a dot.

In the second case, "parseFloat" converts the string to a floating value and "toFixed(2)" declares that there must be 2 decimal places after the point.

If it is necessary to return the mask, do so:

var clean = 1250.50;

var masked = "R$ " + parseFloat(clean).toFixed(2)
   .replace('.',',')
   .replace(/([0-9]*)([0-9]{3},*)/, '$1.$2');
   
alert(masked);

Explaining:

  1. parseFloat(clean). toFixed(2): instance floating number;
  2. .replace('.', ','): replace the point with the comma;
  3. .replace(/([0-9]*)([0-9]{3})/, '$1.$2'): inserts the dot into the thousand

Explaining regular expression "/([0-9]*)([0-9]{3})/":

  1. ([0-9]*): the sentence must start with any number of digits. The parenthesis stores the value found, i.e., "1";
  2. ([0-9]{3},*): the sentence must end with 3 digits, followed by a comma and any later characters. The parenthesis stores the value found, i.e., "250.50";
  3. '$1.$2': creates a string containing the value stored by the two parentheses and concatenates them with a dot ".". That is, R$ 1,250.50.
  • Hello Ricardo. Right. I used your code and it worked, but how would I make it so that in the visualization of the total value, you get to keep the mask? I tried to do this way, but it didn’t work. See: retorno = "R$ " + valorT.toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+\,)/g, "$1.");

  • I did it this way, but it’s returning me this way: 1250,00 and not 1,250,00. valorFinal = "R$ " + parseFloat(valorT).toFixed(2).replace('.',',');

  • 1

    The answer was reformulated with the solution.

  • Perfect Ricardo. It worked!! Thank you very much!

2

If values always come in these formats:

R$ 12.000.000,00
R$ 12.000,00
R$ 12,00

You can create a function that does the following:

  • Remove the R$ preceding all the values;
  • Remove all points (.) (that separate the house from the thousands);
  • Replace the comma (,) by a point (,) (so that the parseFloat work properly);
  • Set the decimal number to two (for this we will use the Number.prototype.toFixed).

Thus:

function numberify(value) {
  return parseFloat(
    value
      .trim()
      .replace(/^R\$ +/, '')
      .replace(/\./g, '')
      .replace(/,/, '.')
  ).toFixed(2)
}

console.log(numberify('R$ 12.000.000,50'))
console.log(numberify('R$ 12.000,00'))
console.log(numberify('R$ 12,25'))


Note: You can reduce the number of uses of replace from three to two. I used one more than necessary to stay a little longer "understandable". :)

function numberify(value) {
  return parseFloat(
    value
      .trim()
      .replace(/^R\$ +|\./g, '')
      .replace(/,/, '.')
  ).toFixed(2)
}

console.log(numberify('R$ 12.000.000,50'))
console.log(numberify('R$ 12.000,00'))
console.log(numberify('R$ 12,25'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.