RSS
 

Test if the given value is a decimal number or not in JavaScript using Regular Expression

26 May

To identify in JavaScript whether the number or a string is in a decimal format or not, is actually pretty easy and short.
It looks obvious, but actually it doesn’t due to several different combinations of decimal number representation in JavaScript.

I’m using Regular Expression to test it:

1
2
3
function isDecimal(number) {
    return /^\d+(\.\d+|e)(e?-\d+)?$/.test(number);
}


Valid inputs:

1
2
3
4
5
6
.12
0.12
123.456
1e-1
1.23e-1
1.23e+1

Not valid inputs:

1
2
3
4
5
6
7
8
9
10
0
123
123.
123.0
.0
0.0
0e+1
1.23e+2
100e-2
1123456789012345678901234567890 //which is actually 1.1234567890123457e+30

I couldn’t find it on Google, so I thought to share it with you.

Cheers!

 

Tags: , , , , , , ,

Leave a Reply