How to validate decimal numbers in javascript with examples
- Admin
- Sep 20, 2023
- Javascript-examples
In this tutorial, You learned how to validate decimal numbers in javascript.
A decimal number is a number that is separated by a .symbol
For example, 12.01,22.912 are decimal numbers.
In UI form, There are different form validation errors like email, not required, and number only.
Sometimes an input form wants validation for decimal numbers only.
There are multiple ways we can check
How to check a given number is decimal or not using regular expression in javascript
- Written a function
isDecimal
, returnstrue
for decimals andfalse
for non-decimals. - Used regular expression string that checks strings containing the
.
symbol with numbers only - javascript
test
method checks the input string with a regular expression and returns a boolean value
Here is an example of checking decimal numbers or not
function isDecimal(input) {
let regex = /^[-+]?[0-9]+\.[0-9]+$/;
return regex.test(input);
}
console.log(isDecimal(12.23)); //true
console.log(isDecimal(12)); //false
console.log(isDecimal(0.12)); //true
console.log(isDecimal(-12.121213212)); //true
console.log(isDecimal(-12)); //false
Validation number to allow 2 decimal numbers only in javascript
Sometimes, need validation to allow 2 decimal numbers only.
For example, 11.34 is 2 digits after decimal numbers only, 45.23423 is not 2 digit decimals and returns false.
function isDecimal(input) {
var regex = /^\d+\.\d{0,2}$/;
return regex.test(input);
}
console.log(isDecimal(12.23)); //true
console.log(isDecimal(12)); //false
console.log(isDecimal(0.12)); //true
console.log(isDecimal(-12.121213212)); //false
console.log(isDecimal(-12)); //false
Conclusion
You learned how to check whether the given input is a decimal number or not and also check if the input form has a 2-digit after decimal numbers.