javascript 如何检查字符串是否为自然数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16799469/
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
How to check if a string is a natural number?
提问by omega
In javascript, how can you check if a string is a natural number (including zeros)?
在javascript中,如何检查字符串是否为自然数(包括零)?
Thanks
谢谢
Examples:
例子:
'0' // ok
'1' // ok
'-1' // not ok
'-1.1' // not ok
'1.1' // not ok
'abc' // not ok
回答by rlemon
Here is my solution:
这是我的解决方案:
function isNaturalNumber(n) {
n = n.toString(); // force the value incase it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
Here is the demo:
这是演示:
var tests = [
'0',
'1',
'-1',
'-1.1',
'1.1',
'12abc123',
'+42',
'0xFF',
'5e3'
];
function isNaturalNumber(n) {
n = n.toString(); // force the value incase it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
console.log(tests.map(isNaturalNumber));
here is the output:
这是输出:
[true, true, false, false, false, false, false, false, false]
[真、真、假、假、假、假、假、假、假]
DEMO:http://jsfiddle.net/rlemon/zN6j3/1
演示:http : //jsfiddle.net/rlemon/zN6j3/1
Note: this is not a true natural number, however I understood it that the OP did not want a real natural number. Here is the solution for real natural numbers:
注意:这不是一个真正的自然数,但是我明白 OP 不想要一个真正的自然数。这是实数自然数的解:
function nat(n) {
return n >= 0 && Math.floor(n) === +n;
}
provided by @BenjaminGruenbaum
回答by Chris Bier
Use a regular expression
使用正则表达式
function isNaturalNumber (str) {
var pattern = /^(0|([1-9]\d*))$/;
return pattern.test(str);
}
The function will return either true
or false
so you can do a check based on that.
该函数将返回其中之一true
,false
因此您可以基于此进行检查。
if(isNaturalNumber(number)){
// Do something if the number is natural
}else{
// Do something if it's not natural
}
回答by Blender
If you have a regex phobia, you could do something like this:
如果你有正则表达式恐惧症,你可以这样做:
function is_natural(s) {
var n = parseInt(s, 10);
return n >= 0 && n.toString() === s;
}
And some tests:
还有一些测试:
> is_natural('2')
true
> is_natural('2x')
false
> is_natural('2.0')
false
> is_natural('NaN')
false
> is_natural('0')
true
> is_natural(' 2')
false
回答by Denys Séguret
You could use
你可以用
var inN = !!(+v === Math.abs(~~v) && v.length);
The last test ensures ''
gives false
.
最后一个测试确保''
给出false
。
Note that it wouldn't work with very big numbers (like 1e14
)
请注意,它不适用于非常大的数字(例如1e14
)
回答by karthikr
You can do if(num.match(/^\d+$/)){ alert(num) }
你可以做 if(num.match(/^\d+$/)){ alert(num) }
回答by Goran Lepur
You can check for int with regexp:
您可以使用正则表达式检查 int:
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('Natural');
}
回答by Diode
function isNatural(num){
var intNum = parseInt(num);
var floatNum = parseFloat(num);
return (intNum == floatNum) && intNum >=0;
}
回答by user2000008
Number() parses string input accurately. ("12basdf" is NaN, "+42" is 42, etc.). Use that to check and see if it's a number at all. From there, just do a couple checks to make sure that the input meets the rest of your criteria.
Number() 准确解析字符串输入。(“12basdf”是 NaN,“+42”是 42,等等)。用它来检查它是否是一个数字。从那里,只需进行几次检查以确保输入满足您的其余标准。
function isNatural(n) {
if(/\./.test(n)) return false; //delete this line if you want n.0 to be true
var num = Number(n);
if(!num && num !== 0) return false;
if(num < 0) return false;
if(num != parseInt(num)) return false; //checks for any decimal digits
return true;
}
回答by kennebec
function isNatural(n){
return Math.abs(parseInt(+n)) -n === 0;
}
This returns false for '1 dog', '-1', '' or '1.1', and returns true
对于 '1 dog'、'-1'、'' 或 '1.1',这将返回 false,并返回 true
for non-negative integers or their strings, including '1.2345e12', and not'1.2345e3'.
对于非负整数或其字符串,包括“1.2345e12”,而不是“1.2345e3”。
回答by McNally Paulo
function isNatural(number){
var regex=/^\d*$/;
return regex.test( number );
}