Validating Natural Numbers
Testing functions from here:
http://stackoverflow.com/questions/16799469/how-to-check-if-a-string-is-a-natural-number
Also, here I demonstrate my own solution which should pass all the tests.
JavaScript
// Comment the following line if you just want to see
// the number of failures for each function.
var verbose = true;
//
// Remember to open the console to see the output.
//
// -----------------------------------------------------------------------------
//
// Setup the contending functions.
//
// http://stackoverflow.com/a/16799758/1935675
function isNaturalNumber1(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;
}
// http://stackoverflow.com/a/16799509/1935675
function isNaturalNumber2(str) {
var pattern = /^(0|([1-9]\d*))$/;
return pattern.test(str);
}
// http://stackoverflow.com/a/20464558/1935675
// http://stackoverflow.com/a/16799575/1935675
// http://stackoverflow.com/a/16799493/1935675
function isNatural1(number){
var regex=/^\d*$/;
return regex.test( number );
}
// http://stackoverflow.com/a/16800886/1935675
function isNatural2(n){
return Math.abs(parseInt(+n)) -n === 0;
}
// http://stackoverflow.com/a/16800449/1935675
function isNatural3(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;
}
// http://stackoverflow.com/a/16799633/1935675
function isNatural4(num){
var intNum = parseInt(num);
var floatNum = parseFloat(num);
return (intNum == floatNum) && intNum >=0;
}
// http://stackoverflow.com/a/16799494/1935675
function isNatural5( s ) {
var n = +s;
return !isNaN(n) && n >= 0 && n === Math.floor(n);
}
// http://stackoverflow.com/a/16799538/1935675
function is_natural(s) {
var n = parseInt(s, 10);
return n >= 0 && n.toString() === s;
}
// http://stackoverflow.com/a/16799488/1935675
// Modified it to be a function.
function inN(v) {
return !!(+v === Math.abs(~~v) && v.length);
}
//...