How to validate decimal numbers in javascript


In this tutorial, You learned how to validate decimal numbers in javascript

Decimal number is a number which are 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.

Some times an input form wants validation for decimal numbers only.

There are multiple ways we can check

regular expression to whether 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 regular expression and returns boolean value

Here is an example for checking decimal number 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 decimal number or not and also check if input form has a 2 digit after decimal numbers

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.