Javascript parse float is ignoring the decimals after my comma

Here's a simple scenario. I want to show the subtraction of two values show on my site:

//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 anyone tell me what I'm doing wrong?


This is "By Design". The parseFloat function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.

  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat

To fix this convert the commas to decimal points.

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

javascript's parseFloat doesn't take a locale parameter. So you will have to replace , with .

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

parseFloat parses according to the JavaScript definition of a decimal literal, not your locale's definition. (E.g., parseFloat is not locale-aware.) Decimal literals in JavaScript use . for the decimal point.


Why not use globalize? This is only one of the issues that you can run in to when you don't use the english language:

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

Some links on stackoverflow to look into:

  • Jquery Globalization
  • Globalization in JQuery is not working

As @JaredPar pointed out in his answer use parseFloat with replace

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

Just replacing the comma with a dot will fix, Unless it's a number over the thousands like 1.000.000,00 this way will give you the wrong digit. So you need to replace the comma remove the dots.

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

By using two replaces you'll be able to deal with the data without receiving wrong digits in the output.