Compiled code

How to convert a string to number in JavaScript or TypeScript

It's very easy to work with the numbers in the JavaScript or TypeScript programming language. There is a nice API that allows you to perform many of the mathematical operations.

However, there may be a situation when the number is given in a string variable. This can occur when data is sent over the network, or if some values are taken from the database.

Of course, regular mathematical operators will not work with strings. In such a case, you need to convert that value to the number type and then perform the required operation.

This article provides various methods that you can use to convert a string to a number. You may choose a solution that is the most suitable in your specific case.

Using the parseInt() function

The first method is to use the default parseInt() function. You have to pass the string as an argument into that function. Then, it will return the parsed value as a number.

Please review the following sample. After the conversion, the number will be printed to the console.

let numberValue = parseInt("789");

console.log(numberValue);

Also, it is worth mentioning that if the input value is not correct, the parseInt() function will return a special NaN value.

Below, you can see the full specification of the parseInt() function.

parseInt(string, radix)

As you see, there is an additional radix parameter. You can use it to specify a base for conversion in a range of between 2 and 36. By default, if radix is not set, then the function will try to determine the base from the string. For regular numbers, it may be 10. However, if you provide hexadecimal or octal numbers, the radix will be set accordingly.

Using the parseFloat() function

In addition, there is a function in JavaScript that allows us to parse a string containing a floating point number. Please see the following sample. The parseFloat() function is called with a single argument. The given value is converted to a number and then printed to the console.

let numberValue = parseFloat("789.57");

console.log(numberValue);

The specification of that function is very simple and is given below.

parseFloat(string)

As you can see, the parseFloat() function accepts only a single value. There is no need to provide the radix value, as like it was done for the previous method.

Also, you can pass numbers in various formats. Both regular decimal and exponential numbers are accepted. You may also pass the "Infinity", or "-Infinity" values, they will be parsed accordingly.

It's important to note that if the given value is not in a correct format, the parseFloat() function will return the NaN value.

Unary "+" operator

There is a quick method that allows you to convert a string to a number. You may use the single "+" unary operator that is placed before the string.

Please see the following sample. There is a "+" symbol before the stringValue variable.

let stringValue = "789";
let numberValue = +stringValue;
console.log(numberValue);

It is worth mentioning that the "+" unary operator is also capable of converting other values, not just numbers. For example, the true value will be converted to 1. The false and null values are converted to 0.

As you see, this method is very attractive. You just need to add a single character. However, on another side, it may be hard to notice a plus sign if someone is quickly reading the code. In other words, web developers may not see that some code has a type conversion. This can be a problem during code review. But, it's for you to decide whether to use this method or not in your project.

Using the "Number" class

The Number class is a special type in JavaScript that allows you to store numbers. It can hold both floating point numbers and regular integer values. However, you can use this class to convert some string to a number.

When the Number() is called like a function, it performs type conversion. In that case, you need to pass a single value only. It can be a string holding the desired value.

Please see the following sample.

let stringValue = "789";
let numberValue = Number(stringValue);
console.log(numberValue);

If you run the provided code, you should see a converted number in your console. Also, please pay attention, there is no "new" keyword in our code. If you do use it, the Number() constructor will return an object. But if it is used without the "new" keyword, you will get a primitive of the number.

In addition, the Number class can work with values provided in various formats. For example, you can pass a string with a value stored in hexadecimal or octal formats. In addition, the constructor can accept exponential numbers, null, true and false values, or Infinity constant.

It is worth mentioning that if the given value is not correct, the Number() function will return the NaN primitive.

Checking if a number is valid

As you have probably noticed, most of the functions shown above may return the NaN value. It tells us that the number is not valid. As a result, you may also want to ensure that the returned value is correct or not. To make such a test, you can use the isNaN() function.

Please review the following sample. There, we test if the numberValue variable contains a valid number.

if (isNaN(numberValue)) {
    // The given number is not valid
}

Such a simple code can be very helpful. It allows you to detect if there is some issue with a number. If the number is not correct, you may try to obtain the number again from the source of data. Optionally, you can log the error to console or notify the user about the issue.

Checking type of a variable in TypeScript

There may be a case when you do not know if the given value is a string or number. The TypeScript language allows you to solve such an issue very quickly.

You can create a special function that accepts a parameter in both types. Then, during runtime, you can use the "typeof" operator to check the type of the given value. If it's a string, then we perform a conversion and return the new number back to the caller. However, if the passed value is already a number, then we don't perform any type conversion and simply return the same value back.

Below, you can see our example. Please pay attention, you may need to use TypeScript compiler to run the given sample, since there are types in code.

function toNumber(value: number | string): number {
    if (typeof value === 'string') {
        return Number(value);
    } else {
        return value;
    }
}

The usage of the given function is very simple. Now, we can test if it works, please see the following code.

const value1 = toNumber("123");
const value2 = toNumber(123);

if (value1 === value2) {
    console.log('Values are equal');
}

After running the above example, the console will contain the "Values are equal" message. That's because the toNumber() function returned the same number.

Stripping non-digit symbols from a string

There may be a situation when you are not sure that the string contains a valid number. For example, it can occur when you are reading a user-input data and then trying to parse the numbers. However, the received user-based values may contain letters or other non-digit symbols.

To solve such an issue, you may use the code like the following. We've created a function stripLetters() that removes all non-digit symbols from a single parameter. New value is returned back to the caller.

function stripLetters(value: string): string {
    return value.replace(/\D/g, '');
}

Now, you can see our example that shows how to use the above function. Code is given below.

let stringValue = "a789def";
let numberValue = Number(stripLetters(stringValue));
console.log(numberValue);

At the beginning, we assign a sample string to the "stringValue" variable. Then, the unneeded letters are removed from that value. After that, the result is converted to the number and printed to the console.

It is worth mentioning that the step of removing non-digit symbols is optional. It may not be required in all situations. If you are sure that the given value is correct, you may avoid removing letters from a string.

Limit number of decimal places

If the given value is too long, you may consider using the toFixed() method. It allows you to set the number of digits to keep after the decimal point.

Please pay attention that the generated value will be returned in a string format.

Following is our example that shows how to limit the number of decimal places.

let numberValue = parseFloat("789.1234567").toFixed(3);

console.log(numberValue);

If you run the above code, the console may have the output like this:

789.123

Conclusion

As you can see, it's very easy to work with the numbers in JavaScript or TypeScript programming languages. There are many different ways that allow you to convert a string to a number. Each method has advantages and disadvantages.

If you are not sure if the given string contains floating point number or regular integer, then you can try to use the Number() function. It will detect the type automatically.

Otherwise, if you are sure that you have only integer values in a string, you may use the parseInt() function. In an opposite case, for the floating point numbers, you may consider using the parseFloat() function.

Related Articles

Front end code

Checking if a variable exists in JavaScript or TypeScript

Man typing on laptop

How to send AJAX request in the WordPress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *