Javascript parse float ignores decimal places

Here is a simple scenario. I want to show the subtraction of two values ​​on my website:

//Value on my websites HTML is: "75,00" var fullcost = parseFloat($("#fullcost").text()); //Value on my websites HTML is: "0,03" var auctioncost = parseFloat($("#auctioncost").text()); alert(fullcost); //Outputs: 75 alert(auctioncost); //Ouputs: 0 

Can someone tell me what I am doing wrong?

+44
javascript parsefloat
Sep 27 2018-11-11T00:
source share
6 answers

This is "By Design." The parseFloat function will only consider parts of a string until it reaches a value other than +, -, a number, an exponent, or a decimal point. When he sees a comma, he stops looking and only considers part "75".

To fix this, convert the commas to decimal points.

 var fullcost = parseFloat($("#fullcost").text().replace(',', '.')); 
+87
Sep 27 2018-11-11T00:
source share

javascript parseFloat does not accept locale parameter. Therefore, you will need to replace , by .

 parseFloat('0,04'.replace(/,/, '.')); // 0.04 
+16
Sep 27 2018-11-11T00:
source share

parseFloat parses the definition of a decimal literal , not your locale, in JavaScript. (For example, parseFloat not supported by the locale.) Decimal literals in JavaScript use . for decimal point.

+12
Sep 27 2018-11-11T00:
source share

Why not use globalization? This is just one of the problems you may encounter when you are not using English:

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

Some stackoverflow links to view:

  • JQuery globalization
  • Globalization in jQuery not working
+11
Dec 27 '13 at 17:29
source share

As @JaredPar pointed out in his answer , use parseFloat with replacement

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

Only replacing comma with dot will be fixed. If not , a number over thousands, for example 1.000.000,00 , will lead to an incorrect digit. Therefore you need to replace comma remove dots .

 // Remove all dot's. Replace the comma. var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.')); 

Using two substitutions, you can process the data without getting the wrong numbers in the output.

+7
Mar 17 '14 at 12:07
source share

Numbers in JS use a character . (full stop / period) to indicate a decimal point not a , (comma).

+5
Sep 27 2018-11-11T00:
source share



All Articles