javascript 如果数字大于数字 [英] javascript if number greater than number
本文介绍了javascript 如果数字大于数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个 javascript 函数来验证一个数字是否大于另一个数字
I have this javascript function to validate if a number is greater than another number
function validateForm() {
var x = document.forms["frmOrder"]["txtTotal"].value;
var y = document.forms["frmOrder"]["totalpoints"].value;
if (x > y) {
alert("Sorry, you don't have enough points");
return false;
}
}
由于某种原因它不起作用.
It's not working for some reason.
如果我执行 alert(x)
我得到 1300,而 alert(y)
得到 999
If I do alert(x)
I get 1300, and alert(y)
gives 999
这有效....
function validateForm() {
var x = 1300;
var y = 999;
if (x > y) {
alert("Sorry, you don't have enough points");
return false;
}
}
推荐答案
你应该在比较之前将它们转换为数字.
You should convert them to number before compare.
试试:
if (+x > +y) {
//...
}
或
if (Number(x) > Number(y)) {
// ...
}
注意: parseFloat
和 pareseInt
(比较整数,需要指定radix) 会给你 NaN
一个空字符串,与 NaN
比较总是 false
,如果你不想要将空字符串视为 0
,然后您可以使用它们.
Note: parseFloat
and pareseInt
(for compare integer, and you need to specify the radix) will give you NaN
for an empty string, compare with NaN
will always be false
, If you don't want to treat empty string be 0
, then you could use them.
这篇关于javascript 如果数字大于数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文