简体   繁体   English

在jQuery中检测数字是否为INT或FLOAT

[英]Detect if number is INT or FLOAT in jquery

I am currently taking input in a text-box and on-submit, I am validating the input, the input needs to be a number greater than 0, it should be integer and not contain decimal point. 我目前正在文本框中接受输入并提交,正在验证输入,输入必须是大于0的数字,它应该是整数且不包含小数点。 The problem is I am not able to find any method by which we can detect it is integer or contains decimal point. 问题是我找不到任何方法可以检测到它是整数还是包含小数点。 Here is the code I am using. 这是我正在使用的代码。

    txt[5] = $(this).parents('p').find('input:text').val();
    if (txt[5] == "" || isNaN(txt[5]) || txt[5] <= 0) 
    {
        alert("Incorrect Quantity");
        return false;
    }

Basically as you see I am validating the input given by user, I want to show them a message if the input is wrong, so I am currently using txt[5]%1!=0 to make sure only INT is allowed, but I am open to new answers. 基本上如您所见,我正在验证用户给出的输入,如果输入错误,我想向他们显示一条消息,因此我目前正在使用txt [5]%1!= 0来确保仅允许使用INT,但是我愿意接受新的答案。

The simplest way is to parse the text as a Number, coerce to integer, and see if they are equal: 最简单的方法是将文本解析为数字,强制转换为整数,然后查看它们是否相等:

var numbertxt5 = Number(txt[5]);
if(numbertxt5 | 0 == numbertxt5) { /* int */
} else if (!isNaN(numbertxt5)) { /* float */
} else { /* not a number */
txt[5] = parseInt($(this).parents('p').find('input:text').val(), 10);

这不会验证数字(请参阅Nirk的答案 ),但是如果它不是整数,它将被转换为1。

That is because JavaScript has only one numerical type called number . 那是因为JavaScript只有一种称为number数字类型。 It is neither int nor float , but it behaves like both at a time. 它既不是int也不是float ,但是一次又像。 However, you do have two methods that you can use for this parseInt and parseFloat . 但是,您确实有两种方法可用于此parseIntparseFloat

var result = parseInt($(this).parents('p').find('input:text').val());
txt[5] = result;

Using parseFloat is similar. 使用parseFloat相似。 Eg. 例如。

var result = parseFloat($(this).parents('p').find('input:text').val());
txt[5] = result;

The second example is not what you want but it is here just for your reference. 第二个示例不是您想要的,但在这里仅供参考。

UPDATE: @bfavaretto made a good point with using radix which I omitted in parseInt . 更新:@bfavaretto通过使用我在parseInt省略的基数提出了一个很好的观点。 Have a look at this page for reference http://www.w3schools.com/jsref/jsref_parseint.asp 看看这个页面以供参考http://www.w3schools.com/jsref/jsref_parseint.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM