JavaScript Check If String Is Number: 3 Best Ways

Are you tired of dealing with string inputs in JavaScript and wondering how to check if a string is a number? Look no further! When working with user inputs or data from external sources, it’s very important to verify whether a string is a valid number in JavaScript. Without proper validation, your code may encounter unexpected errors or produce inaccurate results.

In this comprehensive guide, we will explore:

  • Multiple methods to check if a string is a number in JavaScript
  • Using built-in functions like isNaN(), Number() and regular expressions (regex)
  • How to check if the string is a number or decimal
  • Check if string contains only number

By the end of this blog, you’ll have a clear understanding of different approaches to validating numeric strings, whether it’s checking for whole numbers, decimals, or even individual characters.

Why do you need to check if a string is a number in JavaScript?

JavaScript is a loosely typed language, which means that variables do not have fixed data types. This can be convenient and flexible, but it can also lead to some unexpected behaviors and errors. 

For example, if you try to perform arithmetic operations on strings that contain numbers, you may get unexpected results:

let number1 = "10";
let number2 = "20";
console.log(number1 + number2); // Output: "1020"
console.log(number1 - number2); // Output: -10
console.log(number1 * number2); // Output: 200
console.log(number1 / number2); // Output: 0.5

As you can see, the + operator concatenates the strings, while the other operators convert the strings to numbers and perform the calculations. This can be confusing and inconsistent, especially if you are not sure if the strings are numbers or not. Therefore, it is important to check if a string is a number before performing any arithmetic operations or type conversions.

How to check if a string is a number in JavaScript using different methods

We are going to use three different approaches to check if string is number or not.

JavaScript Check If String Is a Number
JavaScript Check If String Is a Number

1. Using the isNaN() function to check if a string is a number

The isNaN() function is a built-in JavaScript method that determines if a value is NaN (Not-a-Number). While it can be used to check if a JavaScript String is a number, it has some caveats to consider.

const isValidNumber = (input) => {
  return !isNaN(input);
}

console.log(isValidNumber("10"));   // Output: true
console.log(isValidNumber("10.2")); // Output: true
console.log(isValidNumber(""));     // Output: true
console.log(isValidNumber(null));   // Output: true
console.log(isValidNumber(true));   // Output: true
console.log(isValidNumber("10a"));  // Output: false

However, there are some drawbacks of using this method. The isNaN() function will try to convert the value to a number before checking if it is NaN. This means that some values that are not numbers, such as empty strings, boolean values, or null values, will be converted to 0 or 1 and return false. 

2. Using parseInt() check if string is a number

The JavaScript parseInt() function is a built-in function that parses a string and returns an integer. You can use this function to check if a string is an integer by passing the string as an argument and comparing the result with the original string. For example:

const isValidNumber = (input) => {
  return parseInt(input) == input
}

console.log(isValidNumber("10"));   // Output: true
console.log(isValidNumber("10.2")); // Output: false
console.log(isValidNumber(""));     // Output: false
console.log(isValidNumber("10a"));  // Output: true
console.log(isValidNumber(null));   // Output: false

However, there are some drawbacks to using this method. The parseInt() function will only check if the value is an integer, not a number. This means that it will return false for any string that contains a decimal point, even if it is a valid number.

3. Check if string is number using the parseFloat() function

The JavaScript parseFloat() function is a built-in function that parses a string and returns a floating-point number. You can use this function to check if a string is a number by passing the string as an argument and comparing the result with the original string. For example:

const isValidNumber = (input) => {
  return parseFloat(input) == input
}

console.log(isValidNumber("10"));   // Output: true
console.log(isValidNumber("10.2")); // Output: true
console.log(isValidNumber(""));     // Output: false
console.log(isValidNumber("10a"));  // Output: false
console.log(isValidNumber(null));   // Output: false

It will return true if the input string contains integer or decimal numbers, otherwise false.

4. Check if string is number using the Number() function

Another method to check if a string is a number in JavaScript is by using the Number() function. It attempts to convert the given value into a number and returns NaN if the conversion fails.

const isValidNumber = (input) => {
  return !isNaN(Number(input));
}

console.log(isValidNumber("10"));   // Output: true
console.log(isValidNumber("10.2")); // Output: true
console.log(isValidNumber(""));     // Output: true
console.log(isValidNumber("10a"));  // Output: false
console.log(isValidNumber(null));   // Output: true
console.log(isValidNumber(false));  // Output: true

Using Number() allows you to explicitly check if a string is a number. However, the Number() function will convert JavaScript empty string, null, and boolean values to 0, so it will return unexpected results.

5. Regular expression (Regex) method

Regular expressions provide a powerful tool for validating strings. You can use a regex pattern to check if a string is a number in JavaScript.

const isValidNumber = (input) => {
  const regex = /^-?\d+(\.\d{1,2})?$/
  return regex.test(input);
}

console.log(isValidNumber("10"));   // Output: true
console.log(isValidNumber("10.2")); // Output: true
console.log(isValidNumber(""));     // Output: false
console.log(isValidNumber("10a"));  // Output: false
console.log(isValidNumber(null));   // Output: false
console.log(isValidNumber(false));  // Output: false
Here, we use the regex pattern /-?\d+/g to check integers or /^-?\d+(\.\d{1,2})?$/ to check floating-point numbers, which match any string containing only numeric characters from start to end. This method offers precise control over what is considered a number, but it requires understanding regular expressions.

How to choose the best method for checking if a string is a number in JavaScript

As you can see, there is no one perfect method for checking if a string is a number in JavaScript. Each method has its strengths and weaknesses, and you may need to use different methods depending on your specific use case and requirements.

Here are some general guidelines to help you choose the best method for your situation:

  • If you want to check if a string is a number in a broad sense, meaning that it can be any kind of number, such as an integer, a decimal, a fraction, or a scientific notation, you can use the parseFloat() method with some additional checks.
    This method is simple and easy to use, and it can handle most of the common formats and values. However, you should also check the type of the value using the typeof operator, and make sure that the value is not NaN, Infinity, or –Infinity.
  • If you want to check if a string is an integer, meaning that it can only be a whole number, you can use the parseInt() method with some additional checks. This method is also simple and easy to use, and it can handle most of the common formats and values.
  • If you want to check if a string is a number in a strict sense, meaning that it has to follow a specific format or pattern, you can use the regular expression

JavaScript check if string is a number or decimal

To check if a string is an integer or a decimal in JavaScript, you can use regular expressions or built-in functions.

1. Check if number is integer or decimal using regular expression

If you need to check for decimal numbers, you can extend the previous regex pattern to accommodate them.
function checkNumberType(input) {
  // Regular expression to match integers and decimals
  var numberPattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;

  if (numberPattern.test(input)) {
    if (input.indexOf('.') !== -1) {
      console.log('The string is a decimal.');
    } else {
      console.log('The string is an integer.');
    }
  } else {
    console.log('The string is neither an integer nor a decimal.');
  }
}

// Test cases
checkNumberType("123");      // Output: The string is an integer.
checkNumberType("3.14");     // Output: The string is a decimal.
checkNumberType("-42.75");   // Output: The string is a decimal.
checkNumberType("12.34.56"); // Output: The string is neither an integer nor a decimal.
checkNumberType("ABC");      // Output: The string is neither an integer nor a decimal.

The regular expression ^[-+]?[0-9]+(\.[0-9]+)?$ is used to match numbers. It allows an optional leading - or + sign, followed by one or more digits, and an optional decimal part with a period and one or more digits.

To test if an input string is a number, we use the test() method of the regular expression object. This method returns true if the string matches the number pattern and false otherwise. Then, we use the JavaScript indexOf() method to look for a decimal point in the string.

  • If the method returns a positive value, it means the string has a decimal point and is a decimal number. 
  • If the method returns -1, it means the string does not have a decimal point and is an integer number.

JavaScript indexOf() String
JavaScript indexOf() String

2. Check if string is integer or decimal using Number.isInteger() method

Number (input) tries to make a number from the string. Number.isInteger() sees if a number has no decimal part. isNaN() sees if a value is not a number at all. These functions help us know if the string is a JavaScript integer, a decimal, or neither.

function checkNumberType(input) {
  if (Number.isInteger(Number(input))) {
    console.log('The string is an integer.');
  } else if (!isNaN(Number(input))) {
    console.log('The string is a decimal.');
  } else {
    console.log('The string is neither an integer nor a decimal.');
  }
}

// Output for different test cases
checkNumberType("123");        // Output: The string is an integer.
checkNumberType("3.14");       // Output: The string is a decimal.
checkNumberType("-42.75");     // Output: The string is a decimal.
checkNumberType("12.34.56");   // Output: The string is neither an integer nor a decimal.
checkNumberType("ABC");        // Output: The string is neither an integer nor a decimal.

These additional approaches provide flexibility and alternative options for handling integer and decimal string checks.

JavaScript check if string is a number only

Sometimes, you may want to ensure that a string only contains numbers, without any extra characters or symbols.

const hasOnlyNumbers = (stringToCheck) => {
  const isNumber = /^[0-9]+$/.test(stringToCheck);
  console.log(isNumber);
}

// Output
hasOnlyNumbers("12"); // true
hasOnlyNumbers("123#"); // false 

By using the regex pattern /^[0-9]+$/, we validate that the string contains only numeric characters. It’s worth noting that this pattern will reject strings with any non-numeric character.

If you want to allow decimal and negative numbers, you can use /^[-+]?[0-9]+(\.[0-9]+)?$/ with this regular expression.

Conclusion

We covered several methods, including isNaN(), Number(), regex, and individual character checks. Remember to choose the method that best suits your specific needs.

To check whether the string is an integer or decimal, you can either use a regular expression or a Number.isInteger() combined  Number() functions

With these methods, you can confidently handle string-to-number validations in your JavaScript applications!

Over to you: which approach are you going to use to check if the string is a number?

Scroll to Top