Receive only number in money field

Asked

Viewed 104 times

3

I’m looking for a td with jQuery.

var linhaTr = $("tbody").find("tr:first-child");

var tamanhoTd = linhaTr.find("td:nth-child(2)").text();

and he returns me for example R$ 5,00. But I need to get back to make calculations the value 5.00. Take out the R$ and change the comma per point...

Moreover...

I wonder if it is "Regular Expressions" that I need to capture the text in a special way, getting only a few things, I need to study this and do not know the name right.

2 answers

4

If the result is R$ 5,00 for example, an initial form may be:

var recuperado = "R$ 5.500,10";
var numero = parseFloat(recuperado.split(" ")[1].replace('.', '').replace(',', '.'));
console.log(typeof numero, numero);

Where the monetary signal is removed, renamed "," to "." and converted to numeric type.

4


If you want you can use regex, in this case it is to capture the important part in that string. It could be something like this (example):

var parteNumerica = string.match(/[\d\.\,]+/);

But you can just break the string and take out the numerical part as the @Lucas Costa mentioned. In this case it is even more important than the string have that exact format.

Then you can do it like this:

var parteNumerica = string.split(' ').pop();

Examples:

Regex:

var string = 'R$ 5.000,50';
var parteNumerica = string.match(/[\d\.\,]+/);
var numero = Number(parteNumerica ? parteNumerica[0].replace(/\./g, '').replace(',', '.') : 0);
console.log(numero);

Regex-free:

var string = 'R$ 5.000.400,50';
var parteNumerica = string.split(' ').pop();
var numero = Number(parteNumerica ? parteNumerica.split('.').join('').replace(',', '.') : 0);
console.log(numero);

  • pop can be more elegant than accessing the index in this case :p

  • I would recommend using regex also in the point replace, because if it is a number in the millions the replace does not take all occurrences of the point. Thus: parteNumerica.replace(/./g, '). replace(',', '.'), would be sure that all point occurrences in the number would be removed

  • It didn’t work, the result is Nan

  • @Brunocabral I fixed, there was a bug. If it doesn’t tell you what the string you’re using.

  • @Gabrielweber well seen! corrected :)

Browser other questions tagged

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