Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating javascript decimal numbers

I'm using the following regexp to validate numbers in my javascript file:

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

It works fine for whole numbers like 100, 200, etc, however for things like 1.44, 4.11, etc, it returns false. How can I change it so numbers with a decimal are also accepted?

like image 539
Ali Avatar asked Mar 22 '10 20:03

Ali


People also ask

How do you check if a number has a decimal in JavaScript?

JavaScript Code:function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place.

How do you validate a number in JavaScript?

Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.

How do you control decimals in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places. This method: Rounds the number. Converts it into a string.

Can you use decimals in JavaScript?

JavaScript has only one type of number. Numbers can be written with or without decimals.


3 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
like image 93
Senseful Avatar answered Oct 24 '22 11:10

Senseful


try this:

^[-+]?\d+(\.\d+)?$
like image 39
hunter Avatar answered Oct 24 '22 09:10

hunter


isNaN seems like a better solution to 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
like image 37
seanmonstar Avatar answered Oct 24 '22 11:10

seanmonstar