Only receive money field number

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 it returns me for example R$ 5,00 . But I need to get back to make calculations the 5.00 value. Take the R $ and change the comma by the point ...

Furthermore ...

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

asked by anonymous 02.01.2017 / 19:45

2 answers

4

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

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

But you can just break the string and take the numeric part as @Lucas Costa mentioned . In this case it is even more important that the string has that format exactly.

In this case you can do this:

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

Examples:

With 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);

No regex:

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

If the result is $ 5.00 for example, an initial form might be:

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

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

    
02.01.2017 / 19:49