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?
JavaScript Code:function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place.
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.
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.
JavaScript has only one type of number. Numbers can be written with or without decimals.
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
try this:
^[-+]?\d+(\.\d+)?$
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With