在 jquery 中检查值是 float 还是 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20311572/
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
Check a value is float or int in jquery
提问by Shiva Krishna Bavandla
I have the following html field, for which i need to check whether the input value is float or int,
我有以下 html 字段,我需要检查输入值是 float 还是 int,
<p class="check_int_float" name="float_int" type="text"></p>
$(document).ready(function(){
$('.check_int_float').focusout(function(){
var value = this.value
if (value is float or value is int)
{
// do something
}
else
{
alert('Value must be float or int');
}
});
});
So how to check whether a value is float or int in jquery.
那么如何在jquery中检查一个值是float还是int。
I need to find/check both cases, whether it is a float, or int, because later if the value was float
i will use it for some purpose and similarly for int
.
我需要查找/检查这两种情况,无论它是浮点数还是整数,因为稍后如果值是,float
我将出于某种目的使用它,对于int
.
回答by Janith Chinthana
use typeof
to check the type, then value % 1 === 0
to identify the int as bellow,
用于typeof
检查类型,然后value % 1 === 0
将 int 识别为波纹管,
if(typeof value === 'number'){
if(value % 1 === 0){
// int
} else{
// float
}
} else{
// not a number
}
回答by Mahmoude Elghandour
You can use a regular expression
您可以使用正则表达式
var float= /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;
var a = $(".check_int_float").val();
if (float.test(a)) {
// do something
}
//if it's NOT valid
else {
alert('Value must be float or int');
}
回答by reto
You can use a regular expression to determine if the input is satisfying:
您可以使用正则表达式来确定输入是否令人满意:
// Checks that an input string is a decimal number, with an optional +/- sign character.
var isDecimal_re = /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/;
function isDecimal (s) {
return String(s).search (isDecimal_re) != -1
}
Keep in mind that the value from the input field is still a string and not a number
type yet.
请记住,输入字段中的值仍然是字符串而不是number
类型。
回答by Rahul Tripathi
I think the best idea would be to check like this ie, to check the remainder when dividing by 1:
我认为最好的办法是像这样检查,即在除以 1 时检查余数:
function isInt(value) {
return typeof value === 'Num' && parseFloat(value) == parseInt(value, 10) && !isNaN(value);
}