[英]How to check if a string is a natural number?
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
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.注意:这不是一个真正的自然数,但是我明白 OP 不想要一个真正的自然数。 Here is the solution for real natural numbers:
下面是实数自然数的解:
function nat(n) {
return n >= 0 && Math.floor(n) === +n;
}
http://jsfiddle.net/KJcKJ/ http://jsfiddle.net/KJcKJ/
provided by @BenjaminGruenbaum由@BenjaminGruenbaum提供
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
}
Source: http://www.codingforums.com/showthread.php?t=148668来源: http : //www.codingforums.com/showthread.php? t= 148668
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
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
)
你可以这样做if(num.match(/^\\d+$/)){ alert(num) }
You can check for int with regexp:您可以使用正则表达式检查 int:
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('Natural');
}
function isNatural(num){
var intNum = parseInt(num);
var floatNum = parseFloat(num);
return (intNum == floatNum) && intNum >=0;
}
Number() parses string input accurately. Number() 准确解析字符串输入。 ("12basdf" is NaN, "+42" is 42, etc.).
(“12basdf”是 NaN,“+42”是 42,等等)。 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.
从那里,只需进行几次检查以确保输入符合您的其余标准。
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;
}
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”。
I know this thread is a bit old but I believe I've found the most accurate solution thus far:我知道这个线程有点旧,但我相信我已经找到了迄今为止最准确的解决方案:
function isNat(n) { // A natural number is...
return n != null // ...a defined value,
&& n >= 0 // ...nonnegative,
&& n != Infinity // ...finite,
&& typeof n !== 'boolean' // ...not a boolean,
&& !(n instanceof Array) // ...not an array,
&& !(n instanceof Date) // ...not a date,
&& Math.floor(n) === +n; // ...and whole.
}
My solution is basically an evolution of the contribution made by @BenjaminGruenbaum.我的解决方案基本上是@BenjaminGruenbaum 所做贡献的演变。
To back up my claim of accuracy I've greatly expanded upon the tests that @rlemon made and put every proposed solution including my own through them:为了支持我对准确性的主张,我极大地扩展了@rlemon 所做的测试,并将每个提议的解决方案(包括我自己的解决方案)通过它们:
http://jsfiddle.net/icylace/qY3FS/1/ http://jsfiddle.net/icylace/qY3FS/1/
As expected some solutions are more accurate than others but mine is the only one that passes all the tests.正如预期的那样,一些解决方案比其他解决方案更准确,但我的解决方案是唯一通过所有测试的解决方案。
EDIT: I updated isNat()
to rely less on duck typing and thus should be even more reliable.编辑:我更新了
isNat()
以减少对鸭子类型的依赖,因此应该更可靠。
const func = (number) => {
return Math.floor(number) === number
}
Convert the string to a number and then check:将字符串转换为数字,然后检查:
function isNatural( s ) {
var n = +s;
return !isNaN(n) && n >= 0 && n === Math.floor(n);
}
function isNatural(number){
var regex=/^\d*$/;
return regex.test( number );
}
This is how I check if a string is a natural number (including zeros).这就是我检查字符串是否为自然数(包括零)的方式。
var str = '0' // ok var str1 = '1' // ok var str2 = '-1' // not ok var str3 = '-1.1' // not ok var str4 = '1.1' // not ok var str5 = 'abc' // not ok console.log("is str natural number (including zeros): ", Number.isInteger(Number(str)) && Number(str) >= 0) console.log("is str1 natural number (including zeros): ", Number.isInteger(Number(str1)) && Number(str1) >= 0) console.log("is str2 natural number (including zeros): ", Number.isInteger(Number(str2)) && Number(str2) >= 0) console.log("is str3 natural number (including zeros): ", Number.isInteger(Number(str3)) && Number(str3) >= 0) console.log("is str4 natural number (including zeros): ", Number.isInteger(Number(str4)) && Number(str4) >= 0) console.log("is str5 natural number (including zeros): ", Number.isInteger(Number(str5)) && Number(str5) >= 0)
function isNatural(n) {
return Number(n) >= 0 && Number(n) % 1 === 0;
}
Why not simply use modulo?为什么不简单地使用模数呢? if(num % 1;== 0) return false;
如果(num % 1;== 0)返回 false;
Use /^\\d+$/
will match 000
.使用
/^\\d+$/
将匹配000
。 so use /^[1-9]\\d*$|^0$/
match positive integer or 0 will be right.所以使用
/^[1-9]\\d*$|^0$/
匹配正整数或 0 将是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.