In this tutorial, You learned how to validate decimal numbers in javascript.
A decimal number is a number which is separated by .symbol
For example, 12.01,22.912 are decimal numbers.
In UI form, There are different form validations 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
regular expression to whether a given number is decimal or not
- Written a function isDecimal, returns true for decimals and false for non-decimals.
- Used regular expression string for separated by .symbol with numbers only
- test method checks input string with a regular expression and returns a boolean value
Here is an example for 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(.12)) //true
console.log(isDecimal(-12.121213212)) //true
console.log(isDecimal(-12)) //false
Validation to allow 2 decimal numbers only
Sometimes, need validation to allow 2 decimal numbers only.
For example 11.34 is a 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(.12)) //true
console.log(isDecimal(-12.121213212)) //false
console.log(isDecimal(-12)) //false
Conclusion
You learned how to check given input is a decimal number or not and also check if the input form has a 2 digit after decimal numbers.