Convert String from a div to int and do a mathematical operation

Asked

Viewed 122 times

1

I’m trying to do the following function:

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

    function calculaParcela(){
    var regex = /\d+,\d+/g;
    var texto = $(".our_price_display").text(); //id da div com o texto R$ 71,90
    var valor = regex.exec(texto);
    var insereValor = $("#valor-parcelado").text(valor.join(""));

    console.log(insereValor);

    var divide = insereValor / 3;

    console.log(divide); 
}

But on the console he returns me Nan.

what could be done to fix this operation?

1 answer

2


Nan is an error returned to non-numeric (not a number). You will have to convert to number using parseFloat:

$("button").click(function() {
  $("#resultado").text(calculaParcela());
});

function calculaParcela() {
  var regex = /\d+,\d+/g;
  var texto = $("#our_price_display").text(); //id da div com o texto R$ 170
  var valor = regex.exec(texto);
  var insereValor = parseFloat(valor.join("").replace(",","."));
  var divide = insereValor / 3;
  return divide;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="our_price_display">R$ 71,90</span>
<br/>
<span id="resultado"></span>
<br/>
<button>Só valor</button>

  • 1

    Man, that’s right! Thank you very much!

Browser other questions tagged

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