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?
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.
The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number.
parseFloat() method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN .
To parse a string with commas to a number:Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas. Convert the string to a number.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With