How to Check if a String is a Number in TypeScript?

In this tutorial, I will explain how to check if a string is a number in TypeScript using various methods with examples. As a TypeScript developer, you may often encounter situations where you need to validate user input or process data that could be in various formats. For example, when dealing with forms that collect numerical data, ensuring that the input is indeed a number is crucial to prevent errors and ensure data integrity.

Check if a String is a Number in TypeScript

Receiving values as strings is common when handling data in TypeScript, especially with user inputs. This can lead to complications when performing mathematical operations or validations.

For example, consider a scenario where a user named John Smith fills out a form to enter his age. If he accidentally inputs “twenty-five” instead of “25”, your application needs to handle this gracefully.

There are several approaches to determine if a string represents a number in TypeScript. Below, I will cover the most common methods, including using built-in functions and regular expressions with examples.

1. Using the isNaN() Function

The isNaN() function is a built-in JavaScript function that can be utilized in TypeScript to check if a value is NaN (Not-a-Number). However, it is essential to note that isNaN() can return true for non-numeric strings, so it should be used carefully.

Here’s how you can use it:

function isStringANumber(value: string): boolean {
    return !isNaN(Number(value)) && value.trim() !== '';
}

console.log(isStringANumber("25")); // true
console.log(isStringANumber("twenty-five")); // false
console.log(isStringANumber("")); // false

Here is the exact output in the screenshot below:

Check if a String is a Number in TypeScript

Check out Convert Date to String Format DD/MM/YYYY in TypeScript

2. Using the Number Constructor

Another straightforward method is to use the Number constructor. This approach converts the string to a number and checks if the conversion was successful.

function isStringANumber(value: string): boolean {
    const num = Number(value);
    return !isNaN(num) && value.trim() !== '';
}

console.log(isStringANumber("100")); // true
console.log(isStringANumber("abc")); // false

3. Regular Expressions

Regular expressions (regex) can be a powerful tool for validating strings. You can create a regex pattern that matches only numeric values.

function isStringANumber(value: string): boolean {
    const regex = /^\d+$/; // Matches only whole numbers
    return regex.test(value.trim());
}

console.log(isStringANumber("123")); // true
console.log(isStringANumber("123abc")); // false
console.log(isStringANumber(" ")); // false

You can see the exact output in the screenshot below;

Python sort list of lists

4. Using typeof with isFinite()

You can also combine typeof with isFinite() to ensure the string is a numeric value. This method checks if the value is a number and is finite.

function isStringANumber(value: string): boolean {
    const num = Number(value);
    return typeof num === 'number' && isFinite(num);
}

console.log(isStringANumber("45.67")); // true
console.log(isStringANumber("NaN")); // false

Check out How to Check if a String is in an Enum in TypeScript?

Practical Example: Validating User Input

Let’s take a practical example to understand how these methods can be used in a real-world application. Imagine you are developing a registration form for a fitness program in the USA where users need to enter their age. Here’s how you can implement the validation:

Step 1: Create the Form

<form id="registrationForm">
    <label for="age">Enter your age:</label>
    <input type="text" id="age" name="age" />
    <button type="submit">Submit</button>
</form>
<div id="message"></div>

Step 2: Implement the Validation Logic

document.getElementById('registrationForm')!.addEventListener('submit', function (event) {
    event.preventDefault();
    const ageInput = (document.getElementById('age') as HTMLInputElement).value;
    const messageElement = document.getElementById('message')!;

    if (isStringANumber(ageInput)) {
        messageElement.textContent = "Thank you for entering your age!";
        messageElement.style.color = "green";
    } else {
        messageElement.textContent = "Please enter a valid number for your age.";
        messageElement.style.color = "red";
    }
});

Step 3: Implement the isStringANumber Function

You can choose any of the previously mentioned methods to implement the isStringANumber function. Here’s an example using regex:

function isStringANumber(value: string): boolean {
    const regex = /^\d+$/; // Matches only whole numbers
    return regex.test(value.trim());
}

Hande Different Cases

When validating strings, it’s essential to consider edge cases:

  • Empty Strings: Should return false.
  • Whitespace: Strings with only spaces should return false.
  • Negative Numbers: If you want to allow negative numbers, adjust your regex accordingly (e.g., /^-?\d+$/).
  • Decimal Numbers: If decimals are allowed, use a regex like /^\d+(\.\d+)?$/.

Example for Handling Decimals

function isStringANumber(value: string): boolean {
    const regex = /^\d+(\.\d+)?$/; // Matches whole and decimal numbers
    return regex.test(value.trim());
}

console.log(isStringANumber("12.34")); // true
console.log(isStringANumber("-12.34")); // false (if negative numbers are not allowed)

Conclusion

In this tutorial, we explored various methods to check if a string is a number in TypeScript, highlighting the importance of input validation in web applications. Whether you choose to use isNaN(), the Number constructor, regular expressions, or a combination of these methods, the key is to ensure that your application handles user input gracefully.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.