javascript 乘法中的 NaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13729247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NaN in multiplication
提问by daniel__
I am trying this code, but i am getting NaN
我正在尝试这个代码,但我得到了 NaN
a = unidade.val();
b = unitario.val();
//alert(a);5
//alert(b);50,00
$(total).val(a * b); //NaN
Why? because is a int*float
?
为什么?因为是int*float
?
回答by Denys Séguret
You have to parse the strings before you multiply as valalways returns a string and "50,00"
can't be converted automatically to a number.
您必须在乘法之前解析字符串,因为val总是返回一个字符串并且"50,00"
不能自动转换为数字。
parseFloat("50,1")
gives you 50
. If the comma here is the decimal separator, you have to replace it with a dot.
parseFloat("50,1")
给你50
。如果这里的逗号是小数点分隔符,则必须将其替换为点。
So you probably need
所以你可能需要
a = parseFloat(unidade.val().replace(",", ".");
b = parseFloat(unitario.val().replace(",", ".");
EDIT :
编辑 :
if you want to allow numbers formatted like 2.500,00
, then I propose this code :
如果您想允许格式为 的数字2.500,00
,那么我建议使用以下代码:
function vf(str) {
return parseFloat(str.replace(".", "").replace(",", "."));
}
a = vf(unidade.val());
b = vf(unitario.val());
But it's dangereous if you have users who prefer (or expect) the American notation. I'd probably stick to the American notation and show an error if the field contains a comma.
但是,如果您的用户更喜欢(或期望)美国符号,那就很危险了。如果该字段包含逗号,我可能会坚持使用美式符号并显示错误。
Note that HTML5 proposes <input type=number>
which forces the user to type number and let you get numbers directly. See reference.
请注意,HTML5 建议<input type=number>
强制用户键入数字并让您直接获取数字。见参考。
回答by Ivan Solntsev
Looks like you get strings from val()
function.
看起来您从val()
函数中获取字符串。
You can use Number
, or parseInt
, or parseFloat
to cast types
您可以使用Number
, or parseInt
, orparseFloat
来转换类型
$(total).val(Number(a) * Number(b));
回答by topcat3
You have to parse the strings before you multiply!
您必须在乘法之前解析字符串!
Note: If the operands are numbers, regular arithmetic multiply is performed, meaning that two positives or two negatives equal a positive, whereas operands with different signs yield a negative. If the result is too high or too low, the result is either Infinity or –Infinity.
注意:如果操作数是数字,则执行常规算术乘法,这意味着两个正数或两个负数等于一个正数,而具有不同符号的操作数产生一个负数。如果结果太高或太低,结果要么是无穷大,要么是 – 无穷大。
If either operand is NaN, the result is NaN.
如果任一操作数为 NaN,则结果为 NaN。
If Infinity is multiplied by 0, the result is NaN.
如果 Infinity 乘以 0,则结果为 NaN。
If Infinity is multiplied by any number other than 0, the result is either Infinity or –Infinity, depending on the sign of the second operand.
如果 Infinity 与 0 以外的任何数字相乘,则结果为 Infinity 或 –Infinity,具体取决于第二个操作数的符号。
If Infinity is multiplied by Infinity, the result is Infinity.
如果无穷大乘以无穷大,结果是无穷大。