Division greater than R$999.00 results in Nan. How to format correctly

Asked

Viewed 120 times

6

Division less than R$999.00 works correctly. However, more than R$999.00 results in Nan. How to revolve this? I’ve already put a replace and nothing!

$(document).ready(function() {
   var demo1 = $('span.ecwid-productBrowser-price-value');
   demo1.each(function() {
   var valor1 = parseInt(this.innerHTML.replace(',', '.').substr(2) / 3, 10);
   $(this).append("<p><i>dividido por 3 é: " + valor1 + "</i></p>")
    })
  demo1.append();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

<body>

<span class='ecwid-productBrowser-price-value'>R$800,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$999,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$1.000,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$1.200,00</span><hr>


</body>

  • 2

    Related https://answall.com/q/11018/101

2 answers

7


The problem is that there are two points when the number is on the order of a thousand. That is, it looks like this: parseInt(1.200.00, 10) and this gives bug.

You have to remove the dots before you turn the comma into a dot.

$(document).ready(function() {
   var demo1 = $('span.ecwid-productBrowser-price-value');
   demo1.each(function() {
   var valor1 = parseInt(this.innerHTML.replace(/\./g, '').replace(',', '.').substr(2) / 3, 10);
   $(this).append("<p><i>dividido por 3 é: " + valor1 + "</i></p>")
    })
  demo1.append();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

<body>

<span class='ecwid-productBrowser-price-value'>R$800,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$999,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$1.000,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$1.200,00</span><hr>


</body>

  • 1

    Okay. I get it. It worked perfectly here!

2

Remove the points from the thousand

$(document).ready(function() {
   var demo1 = $('span.ecwid-productBrowser-price-value');
   demo1.each(function() {
   var valor1 = parseInt(this.innerHTML.replace(',', '.').substr(2) / 3, 10);
   $(this).append("<p><i>dividido por 3 é: " + valor1 + "</i></p>")
    })
  demo1.append();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

<body>

<span class='ecwid-productBrowser-price-value'>R$800,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$999,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$1000,00</span><hr>
<span class='ecwid-productBrowser-price-value'>R$1200,00</span><hr>


</body>

  • I need to keep the point in the mile. I’m capturing a variable innerHTML. But thanks for the suggestion!

  • Frmz @Bamdeveloper... you can make one more replace only at the time of calculation...

Browser other questions tagged

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