Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptHow to Validate Decimal Numbers in JavaScript ?

How to Validate Decimal Numbers in JavaScript ?

Validating user input is an essential aspect of Web Development. As a developer, when we are playing with the numeric inputs provided by the end-user, it is quite important to ensure that the input provided by the user is in the correct format. If the text field is expecting a decimal number and the user is entering the alphabetical value, then it should be handled properly and validated. JavaScript provides a built-in method called “isNumeric” that can be used to validate decimal numbers.  The “isNumeric” method can be used to check wheater ta value is numeric or not. One argument is taken by the isNumeric function, which is “value“. 

The general syntax for the “isNumeric” function is stated below:

Syntax:

function isNumeric(value) {
  return /^-?\d+(\.\d+)?$/.test(value);
}

The function returns the Boolean value: “true” if the value is numeric, else the “false” value will be returned.

Examples 1:Validating a Decimal Number

Javascript




function isNumeric(value) {
      return /^-?\d+(\.\d+)?$/.test(value);
}
  
const value = "3.14";
const isNumber = isNumeric(value);
console.log(isNumber);


Output:

true

Explanation: In this example, the “isNumeric” function/method is used to validate the value “3.14“. The method returns “true” because the “3.14” value is a valid decimal number. The code prints the result “true” in the console. 

Example 2: Validating a non-numeric value

Javascript




function isNumeric(value) {
      return /^-?\d+(\.\d+)?$/.test(value);
}
  
const value = "hello";
const isNumber = isNumeric(value);
console.log(isNumber);


Output: 

false

Explanation: In this example, the “isNumeric” function is used to validate the value “hello“. The function returns “false” because “hello” is not a valid decimal number. The code displays the result as “false” in the console. 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments