How to validate decimal numbers in javascript (examples)

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

A decimal number is a number, that contains precision, separated by a Dot(.) symbol

For example, 12.01, and 22.912 are decimal numbers. Different form-level validations are implemented in UI Form to disallow invalid values.

Sometimes, an input form wants validation for decimal numbers only.

There are multiple ways we can validate given number is Decimal or not

Use regular expression in javascript

  • Written a function isDecimal, returns true for decimals and false for non-decimals.
  • Used regular expression /^[-+]?[0-9]+\.[0-9]+$/, that checks strings containing the . symbol with numbers only
  • The 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

Also, checks even if a Given input is a string.

Check if a Given number contains 2 decimal precisions only in javascript

Sometimes, needs 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.