javascript如果数字大于数字 [英] javascript if number greater than number

查看:156
本文介绍了javascript如果数字大于数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数validateForm(){$ b $我有这个javascript函数来验证数字是否大于另一个数字b var x = document.forms [frmOrder] [txtTotal] .value; 
var y = document.forms [frmOrder] [totalpoints] .value;

if(x> y){
alert(对不起,你没有足够的积分);
返回false;
}
}

由于某种原因,这不起作用。



如果我执行 alert(x),我得到1300, alert(y)

 <$ <$ p $ $ 

c $ c> function validateForm(){
var x = 1300;
var y = 999;

if(x> y){
alert(对不起,你没有足够的积分);
返回false;



$ div $解析方案

你应该将它们转换为比较前的数字。



尝试:

  if (+ x> + y){
// ...
}



<如果(数字(x)>数字(y)){
// ... $ p $或$ p
$ b

  
}

注意: parseFloat pareseInt (用于比较整数,您需要指定基数)会给你一个空字符串 NaN ,与 NaN 比较将永远是 false ,如果你不想把空字符串作为 0 ,那么你可以使用它们。


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.

If I do alert(x) I get 1300, and alert(y) gives 999

This works....

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.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆