Checking javascript decimal numbers

I use the following regexp to check the numbers in a javascript file:

var valid = (val.match(/^\d+$/)); 

It works great for integers like 100, 200, etc., however for things like 1.44, 4.11, etc., it returns false. How can I change it so that decimal numbers are also accepted?

+6
javascript jquery regex
source share
5 answers
 var valid = (val.match(/^\d+(?:\.\d+)?$/)); 

Matches:

  1 : yes 1.2: yes -1.2: no +1.2: no .2: no 1. : no 

 var valid = (val.match(/^-?\d+(?:\.\d+)?$/)); 

Matches:

  1 : yes 1.2: yes -1.2: yes +1.2: no .2: no 1. : no 

  var valid = (val.match(/^[-+]?\d+(?:\.\d+)?$/)); 

Matches:

  1 : yes 1.2: yes -1.2: yes +1.2: yes .2: no 1. : no 

 var valid = (val.match(/^[-+]?(?:\d*\.?\d+$/)); 

Matches:

  1 : yes 1.2: yes -1.2: yes +1.2: yes .2: yes 1. : no 

 var valid = (val.match(/^[-+]?(?:\d+\.?\d*|\.\d+)$/)); 

Matches:

  1 : yes 1.2: yes -1.2: yes +1.2: yes .2: yes 1. : yes 
+27
source share

try the following:

 ^[-+]?\d+(\.\d+)?$ 
+3
source share

isNaN seems like the best solution for me.

 > isNaN('1') false > isNaN('1a') true > isNaN('1.') false > isNaN('1.00') false > isNaN('1.03') false > isNaN('1.03a') true > isNaN('1.03.0') true 
+3
source share

If you want to accept decimal places (including <1) and integers, with optional + or - signs, you can use valid = Number (val).

Or regex:

 valid=/^[+\-]?(\.\d+|\d+(\.\d+)?)$/.test(val); 
0
source share

! isNaN (text) && & parseFloat (text) == text

0
source share

All Articles