Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

Thanks

Examples:

'0' // ok
'1' // ok
'-1' // not ok
'-1.1' // not ok
'1.1' // not ok
'abc' // not ok
like image 271
omega Avatar asked May 28 '13 19:05

omega


People also ask

How do you check if a number is a natural number?

Counting numbers like 1, 2, 3, 4, 5, 6 … Basically, all integers greater than 0 are natural numbers. The natural numbers are the ordinary numbers, 1, 2, 3, etc., with which we count.

How do you check if something is a natural number in Python?

You can check if a string, x , is a single digit natural number by checking if the string contains digits and the integer equivalent of those digits is between 1 and 9, i.e. Also, if x.


1 Answers

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

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:

function nat(n) {
    return n >= 0 && Math.floor(n) === +n;
}

http://jsfiddle.net/KJcKJ/

provided by @BenjaminGruenbaum

like image 105
rlemon Avatar answered Oct 05 '22 23:10

rlemon