Convert div text to number

4

I'm trying to get the text from this structure:

<span id="our_price_display">R$ 71,90</span>

And I would like it to return only 71,90 .

But in the structure I created, I can not get the "R $" from the text and only recognize the numbers.

How could you do this conversion?

    
asked by anonymous 24.11.2016 / 19:44

6 answers

1

Get the value of the element, then make a .split with javascript

var str = $("#our_price_display").html(); //pega valor todo
var res = str.split(" "); //seu valor você pega no res[1]

alert(res[1]);
    
24.11.2016 / 19:57
3

var text = document.getElementById('our_price_display').innerText;

// APENAS DIGITOS E ,
var number = text.replace(/[^\d,]/g, '');
console.log(number);

// NUMERO PARA FLOAT (numeros presupostos que estão corretos em R$ > 1000,00)
var number = number.replace(',', '.');
console.log(parseFloat(number));
<span id="our_price_display">R$ 71,90</span>
    
24.11.2016 / 19:58
3

You can use regex.

/\d+,\d+/g

Where:

  • \d+ = search by numbers
  • , = includes comma
  • /g = global (throughout the string)

Example:

$("button").click(function(){
  var regex = /\d+,\d+/g;
  var texto = $("#our_price_display").text();
  var valor = regex.exec(texto);
  $("#resultado").text(valor.join(""));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><spanid="our_price_display">R$ 71,90</span>
<br/>
<span id="resultado"></span>
<br/>
<button>Só valor</button>
    
24.11.2016 / 19:51
2

You can do this:

var price = document.getElementById('our_price_display');
var formattedPrice = price.innerHTML.replace(/[^\d,]/g, '');

console.log("Valor formatado:", formattedPrice);
<span id="our_price_display">R$ 71,90</span>

The regex will clear anything that is not numeric or comma from the string.

    
24.11.2016 / 19:58
2

var texto = document.getElementById('our_price_display').innerHTML;
var numero = texto.replace(/[^\d,]/g, '');
document.getElementById('resultado').innerHTML = numero;
<span id="our_price_display">R$ 71,90</span>
<div id="resultado"></div>
    
24.11.2016 / 20:02
0

The answers above already solve your problem well, but if you want to take a look at this library link .

I have used it to convert USD text into a game, it is very simple to use and has several monetary formats.

    
26.11.2016 / 18:04