Home  >  Q&A  >  body text

The decimal part after the comma is ignored in floating point number parsing JavaScript

<p>Here is a simple scenario. I want to display the subtraction of two values ​​on my website: </p> <pre class="brush:php;toolbar:false;">//The value on my website is: "75,00" var fullcost = parseFloat($("#fullcost").text()); //The value on my website is: "0,03" var auctioncost = parseFloat($("#auctioncost").text()); alert(fullcost); //Output: 75 alert(auctioncost); //Output: 0</pre> <p>Can anyone tell me what I'm doing wrong? </p>
P粉282627613P粉282627613447 days ago429

reply all(2)I'll reply

  • P粉587970021

    P粉5879700212023-08-22 12:50:38

    The parseFloat function of javascript does not accept regional parameters. So you need to replace , with .

    parseFloat('0,04'.replace(/,/, '.')); // 0.04

    reply
    0
  • P粉635509719

    P粉6355097192023-08-22 00:17:29

    This is "By Design". parseFloat The function only considers parts of the string until it encounters a non- , -, number, exponent, or decimal point. Once it sees the comma, it stops looking and only considers the "75" part.

    To fix this problem, convert commas to decimal points.

    var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

    reply
    0
  • Cancelreply