How to check if string contains only decimal numbers in JavaScript

How to check if string contains only decimal numbers in JavaScript

posted 6 min read

JavaScript, that dances through the web! Today, our quest is to unravel the age-old mystery: how do we check if a string contains only numbers? Fear not, dear coder, for we're about to explore a trove of JavaScript magic with various methods to crack this numeric conundrum wide open.

What is JavaScript?

JavaScript is a high-level, versatile programming language primarily used for web development. It enables interactive and dynamic content on websites, runs on client browsers, node.js runtime environemnt and supports both object-oriented and functional programming paradigms. As a core technology of the web, it enhances user experiences by allowing developers to create responsive and interactive web applications.

What is a number in JavaScript?

In JavaScript, the "number" data type is used to represent numerical values. Numbers in JavaScript can be integers or floating-point numbers (decimals). Here are some examples:

let integerNumber = 42;       // Integer
let floatNumber = 3.14;       // Floating-point number
let scientificNotation = 5e3; // Scientific notation (5000)

JavaScript supports several notations for representing numbers:

  • Decimal Notation: The most common way to represent numbers. It includes integers and floating-point numbers.
    let decimalNumber = 123;    // Integer
    let floatNumber = 3.14;     // Floating-point number
    
  • Scientific Notation: Useful for representing very large or very small numbers. It uses "e" to indicate the power of 10.

    let scientificNumber = 5e3; // 5000
    
  • Binary Notation: Introduced in ECMAScript 6, you can represent numbers in binary using the "0b" prefix.

    let binaryNumber = 0b1010;  // 10 in binary
    
  • Octal Notation: Also introduced in ECMAScript 6, you can represent numbers in octal using the "0o" prefix.

    let octalNumber = 0o765;    // 509 in decimal
    
  • Hexadecimal Notation: You can represent numbers in hexadecimal using the "0x" prefix.

    let hexNumber = 0xFF;       // 255 in decimal
    
Note: It's important to note that JavaScript uses a 64-bit double-precision floating-point format to represent all numeric values. While this format allows a wide range of representable numbers, it can lead to precision issues, especially when dealing with very large or very small numbers. Developers need to be mindful of these characteristics when working with numbers in JavaScript..

Let's say that we have an input element which is for the user's age and we need to verify that the user input is only contains numbers, so our HTML structure will be like the following:





Only Numbers





Now let's add a nice UI verification functionality that changes the input outline color to red or green on typing depending on the return value of the function which will check if the string contains only numbers or not ( we will implement different implementations of this function in the Methods section ).

So after we add the JavaScript code, our HTML code will be like the following:

<!DOCTYPE html>




Only Numbers






const ageInput = document.getElementById("age");

ageInput.addEventListener("input", verificationUI);

function verificationUI(e) {
let outlineColor;
let inputValue = e.target.value;

// isNumber() is our function which will check if the string contains only numbers
outlineColor = isNumber(inputValue) ? "green" : "red";

e.target.style.outlineColor = outlineColor;
}

function isNumber(userInput) {
// any implementation of the Methods section
}


Methods

Method 1: Using Regular Expression

Here we will use regular expressions pattern to check if the input is only digits so our implementation will be like the following:

function isNumber(userInput) {
  return /^\d+(.\d+)?$/.test(userInput);
}

Our regular expression here is very simple. the "^" symbol determine that any character after it is in the first position, "\d" means digits (0-9) and the "+" means at least one digit or more than that, and "(.\d+)" is a capturing group to check for only one "dot" with a following one digit or more, and the "?" after it to check for if the previous capturing group is not presented or at most one time, and finally the "$" determine that any character before it is in the last position, so the digits shouldn't have any non-digit characters before it or after it.

The test() method is for checking if the regular expression pattern is in the string passed to it, in our case userInput, then returns a boolean value (true or false).

Method 2: Using the Number() function

In this method, we will use the Number() function which is converting the string datatype to an number, but to convert the string to number without problems, the string should contain only numbers, otherwise the Number() will return NaN (Not a Number) which tells us that the string contains other characters beside the numbers, so the implementation will be like the following:

function isNumericUsingNumber(str) {
  return !isNaN(Number(userInput));
}

Method 3: Using the string comparison

For those who appreciate simplicity, comparing strings does the trick. By checking if a string is equal to its equivalent when cast as a number, we confirm its numeric nature, so the implementation will be like the following:

function isNumber(userInput) {
  return userInput === String(Number(userInput));
}

So in the above code we are using the Number() function to convert userInput to a number or NaN if it contains other than numbers, then we use the String() function to re-convert it to a string so we can compare it with userInput, then we return the boolean value.

The Full Code

By adding the first method to our HTML, the full code will be like the following:

<!DOCTYPE html>




Only Numbers






const ageInput = document.getElementById("age");

ageInput.addEventListener("input", verificationUI);

function verificationUI(e) {
let outlineColor;
let inputValue = e.target.value;

// isNumber() is our function which will check if the string contains only numbers
outlineColor = isNumber(inputValue) ? "green" : "red";

e.target.style.outlineColor = outlineColor;
}

function isNumber(userInput) {
return !isNaN(Number(userInput));
}


The Output

if the input contains only numbers:

if the input contains numbers with other characters:

Use Cases

Form Validation

Imagine you're validating a form, ensuring user input for age or phone numbers consists only of numbers. These methods act as guardians, safeguarding your forms from unwanted characters.

Data Processing

Handling a dataset from an API where some values arrive as strings? These methods are your go-to tools to ensure you're working with legitimate numeric data.

User Input Handling

When dealing with user input, guaranteeing the input is numeric becomes paramount. These methods act as gatekeepers, ensuring your applications process only the data they expect.

Conclusion

Armed with these JavaScript methods, you're ready for real-world challenges. Whether you're validating user input in forms, processing API data, or ensuring your applications handle only expected numeric input, these tools are your trusty companions. Fear not, for armed with JavaScript, you're set to dance through the intricacies of numeric verification

References:

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

How to display success message after form submit in javascript?

Curtis L - Feb 19, 2024

How to redirect to another page in javascript on button click?

prince yadav - Feb 17, 2024

A Practical guide to Async and Await for JavaScript Developers

Mubaraq Yusuf - Jan 8

Understanding Obfuscation In Javascript

Dhanush Nehru - Jan 12

Unlocking the Power of Generators in JavaScript

Mubaraq Yusuf - Jan 4
chevron_left