Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
Only Bolivian Here Avatar asked Sep 27 '11 15:09

Only Bolivian Here


People also ask

What is parse float in Javascript?

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.

How does parse float work?

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.

What happens if you parseFloat 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 .

How do you convert a string to a comma with numbers?

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.


2 Answers

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(',', '.'));
like image 163
JaredPar Avatar answered Oct 22 '22 05:10

JaredPar


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

parseFloat('0,04'.replace(/,/, '.')); // 0.04
like image 38
Joe Avatar answered Oct 22 '22 04:10

Joe