Validate decimal numbers in JavaScript - IsNumeric()

Viewed 1551373

What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

  1. Clarity. Solution should be clean and simple.
  2. Cross-platform.

Test cases:

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false
51 Answers

Arrrgh! Don't listen to the regular expression answers. RegEx is icky for this, and I'm not talking just performance. It's so easy to make subtle, impossible to spot mistakes with your regular expression.

If you can't use isNaN(), this should work much better:

function IsNumeric(input)
{
    return (input - 0) == input && (''+input).trim().length > 0;
}

Here's how it works:

The (input - 0) expression forces JavaScript to do type coercion on your input value; it must first be interpreted as a number for the subtraction operation. If that conversion to a number fails, the expression will result in NaN. This numeric result is then compared to the original value you passed in. Since the left hand side is now numeric, type coercion is again used. Now that the input from both sides was coerced to the same type from the same original value, you would think they should always be the same (always true). However, there's a special rule that says NaN is never equal to NaN, and so a value that can't be converted to a number (and only values that cannot be converted to numbers) will result in false.

The check on the length is for a special case involving empty strings. Also note that it falls down on your 0x89f test, but that's because in many environments that's an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that's your reason for not using isNaN() then just wrap your own function around isNaN() that can also do the additional check.

In summary, if you want to know if a value can be converted to a number, actually try to convert it to a number.


I went back and did some research for why a whitespace string did not have the expected output, and I think I get it now: an empty string is coerced to 0 rather than NaN. Simply trimming the string before the length check will handle this case.

Running the unit tests against the new code and it only fails on the infinity and boolean literals, and the only time that should be a problem is if you're generating code (really, who would type in a literal and check if it's numeric? You should know), and that would be some strange code to generate.

But, again, the only reason ever to use this is if for some reason you have to avoid isNaN().

This way seems to work well:

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

In one line:

const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);

And to test it:

const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);
    
    function TestIsNumeric(){
        var results = ''
        results += (IsNumeric('-1')?"Pass":"Fail") + ": IsNumeric('-1') => true\n";
        results += (IsNumeric('-1.5')?"Pass":"Fail") + ": IsNumeric('-1.5') => true\n";
        results += (IsNumeric('0')?"Pass":"Fail") + ": IsNumeric('0') => true\n";
        results += (IsNumeric('0.42')?"Pass":"Fail") + ": IsNumeric('0.42') => true\n";
        results += (IsNumeric('.42')?"Pass":"Fail") + ": IsNumeric('.42') => true\n";
        results += (!IsNumeric('99,999')?"Pass":"Fail") + ": IsNumeric('99,999') => false\n";
        results += (!IsNumeric('0x89f')?"Pass":"Fail") + ": IsNumeric('0x89f') => false\n";
        results += (!IsNumeric('#abcdef')?"Pass":"Fail") + ": IsNumeric('#abcdef') => false\n";
        results += (!IsNumeric('1.2.3')?"Pass":"Fail") + ": IsNumeric('1.2.3') => false\n";
        results += (!IsNumeric('')?"Pass":"Fail") + ": IsNumeric('') => false\n";
        results += (!IsNumeric('blah')?"Pass":"Fail") + ": IsNumeric('blah') => false\n";
        
        return results;
    }

console.log(TestIsNumeric());
.as-console-wrapper { max-height: 100% !important; top: 0; }

I borrowed that regex from http://www.codetoad.com/javascript/isnumeric.asp. Explanation:

/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string

Yeah, the built-in isNaN(object) will be much faster than any regex parsing, because it's built-in and compiled, instead of interpreted on the fly.

Although the results are somewhat different to what you're looking for (try it):

                                              // IS NUMERIC
document.write(!isNaN('-1') + "<br />");      // true
document.write(!isNaN('-1.5') + "<br />");    // true
document.write(!isNaN('0') + "<br />");       // true
document.write(!isNaN('0.42') + "<br />");    // true
document.write(!isNaN('.42') + "<br />");     // true
document.write(!isNaN('99,999') + "<br />");  // false
document.write(!isNaN('0x89f') + "<br />");   // true
document.write(!isNaN('#abcdef') + "<br />"); // false
document.write(!isNaN('1.2.3') + "<br />");   // false
document.write(!isNaN('') + "<br />");        // true
document.write(!isNaN('blah') + "<br />");    // false

Use the function isNaN. I believe if you test for !isNaN(yourstringhere) it works fine for any of these situations.

It can be done without RegExp as

function IsNumeric(data){
    return parseFloat(data)==data;
}
return (input - 0) == input && input.length > 0;

didn't work for me. When I put in an alert and tested, input.length was undefined. I think there is no property to check integer length. So what I did was

var temp = '' + input;
return (input - 0) == input && temp.length > 0;

It worked fine.

A couple of tests to add:

IsNumeric('01.05') => false
IsNumeric('1.') => false
IsNumeric('.') => false

I came up with this:

function IsNumeric(input) {
    return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(input);
}

The solution covers:

  • An optional negative sign at the beginning
  • A single zero, or one or more digits not starting with 0, or nothing so long as a period follows
  • A period that is followed by 1 or more numbers

I'd like to add the following:

1. IsNumeric('0x89f') => true
2. IsNumeric('075') => true

Positive hex numbers start with 0x and negative hex numbers start with -0x. Positive oct numbers start with 0 and negative oct numbers start with -0. This one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (4e3.2 is not valid).

function IsNumeric(input){
  var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
  return (RE.test(input));
}

My solution,

function isNumeric(input) {
    var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
    var regex = RegExp(number);
    return regex.test(input) && input.length>0;
}

It appears to work in every situation, but I might be wrong.

Here's a dead-simple one (tested in Chrome, Firefox, and IE):

function isNumeric(x) {
  return parseFloat(x) == x;
}

Test cases from question:

console.log('trues');
console.log(isNumeric('-1'));
console.log(isNumeric('-1.5'));
console.log(isNumeric('0'));
console.log(isNumeric('0.42'));
console.log(isNumeric('.42'));

console.log('falses');
console.log(isNumeric('99,999'));
console.log(isNumeric('0x89f'));
console.log(isNumeric('#abcdef'));
console.log(isNumeric('1.2.3'));
console.log(isNumeric(''));
console.log(isNumeric('blah'));

Some more test cases:

console.log('trues');
console.log(isNumeric(0));
console.log(isNumeric(-1));
console.log(isNumeric(-500));
console.log(isNumeric(15000));
console.log(isNumeric(0.35));
console.log(isNumeric(-10.35));
console.log(isNumeric(2.534e25));
console.log(isNumeric('2.534e25'));
console.log(isNumeric('52334'));
console.log(isNumeric('-234'));
console.log(isNumeric(Infinity));
console.log(isNumeric(-Infinity));
console.log(isNumeric('Infinity'));
console.log(isNumeric('-Infinity'));

console.log('falses');
console.log(isNumeric(NaN));
console.log(isNumeric({}));
console.log(isNumeric([]));
console.log(isNumeric(''));
console.log(isNumeric('one'));
console.log(isNumeric(true));
console.log(isNumeric(false));
console.log(isNumeric());
console.log(isNumeric(undefined));
console.log(isNumeric(null));
console.log(isNumeric('-234aa'));

Note that it considers infinity a number.

No need to use extra lib.

const IsNumeric = (...numbers) => {
  return numbers.reduce((pre, cur) => pre && !!(cur === 0 || +cur), true);
};

Test

> IsNumeric(1)
true
> IsNumeric(1,2,3)
true
> IsNumeric(1,2,3,0)
true
> IsNumeric(1,2,3,0,'')
false
> IsNumeric(1,2,3,0,'2')
true
> IsNumeric(1,2,3,0,'200')
true
> IsNumeric(1,2,3,0,'-200')
true
> IsNumeric(1,2,3,0,'-200','.32')
true

A simple and clean solution by leveraging language's dynamic type checking:

function IsNumeric (string) {
   if(string === ' '.repeat(string.length)){
     return false
   }
   return string - 0 === string * 1
}

if you don't care about white-spaces you can remove that " if "

see test cases below

function IsNumeric (string) {
   if(string === ' '.repeat(string.length)){
      return false
   }
   return string - 0 === string * 1
}


console.log('-1' + ' → ' + IsNumeric('-1'))    
console.log('-1.5' + ' → ' + IsNumeric('-1.5')) 
console.log('0' + ' → ' + IsNumeric('0'))     
console.log('0.42' + ' → ' + IsNumeric('0.42'))   
console.log('.42' + ' → ' + IsNumeric('.42'))    
console.log('99,999' + ' → ' + IsNumeric('99,999'))
console.log('0x89f' + ' → ' + IsNumeric('0x89f'))  
console.log('#abcdef' + ' → ' + IsNumeric('#abcdef'))
console.log('1.2.3' + ' → ' + IsNumeric('1.2.3')) 
console.log('' + ' → ' + IsNumeric(''))    
console.log('33 ' + ' → ' + IsNumeric('33 '))

With regex we can cover all the cases ask in the question. Here it is:

isNumeric for all integers and decimals:

const isNumeric = num => /^-?[0-9]+(?:\.[0-9]+)?$/.test(num+'');

isInteger for just integers:

const isInteger = num => /^-?[0-9]+$/.test(num+'');

Need to check for the null/undefined condition and remove commas (for the US number format) if typeof n === 'string'.

function isNumeric(n)
{
    if(n === null || typeof n === 'undefined')
         return false;

    if(typeof n === 'string')
        n = n.split(',').join('');

    return !isNaN(parseFloat(n)) && isFinite(n);
}

https://jsfiddle.net/NickU/nyzeot03/3/

Well, I'm using this one I made...

It's been working so far:

function checkNumber(value) {
    if ( value % 1 == 0 )
        return true;
    else
        return false;
}

If you spot any problem with it, tell me, please.

Like any numbers should be divisible by one with nothing left, I figured I could just use the module, and if you try dividing a string into a number the result wouldn't be that. So.

The following may work as well.

function isNumeric(v) {
         return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
   };
Related