问题
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?
回答1:
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(',', '.'));
回答2:
javascript's parseFloat doesn't take a locale parameter. So you will have to replace ,
with .
parseFloat('0,04'.replace(/,/, '.')); // 0.04
回答3:
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.
回答4:
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
回答5:
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.
回答6:
Numbers in JS use a .
(full stop / period) character to indicate the decimal point not a ,
(comma).
回答7:
It is better to use this syntax to replace all the commas in a case of a million 1,234,567
var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, "");
var number = parseFloat(string);
console.log(number)
The g
means to remove all commas.
Check the Jsfiddle demo here.
来源:https://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma