Home >Web Front-end >JS Tutorial >Quick Tip: How to Convert a String to a Number in JavaScript

Quick Tip: How to Convert a String to a Number in JavaScript

Christopher Nolan
Christopher NolanOriginal
2025-02-09 10:30:14777browse

Quick Tip: How to Convert a String to a Number in JavaScript

Core points

  • JavaScript provides a variety of ways to convert strings into numbers, including Number() functions, parseInt() and parseFloat() functions, and the unary plus sign ( ) operator. Each method has its own purpose and can be used according to the specific requirements of the code.
  • When converting strings to numbers, it is crucial to handle non-numeric characters. If the string contains characters other than numbers, the Number() function returns NaN, while the parseInt() and parseFloat() functions parse the string if the number is at the beginning of the string and discard the remaining characters.
  • Be sure to note that the return result may be NaN. To check if the value is NaN, you can use the global function isNaN().

JavaScript provides a variety of data type conversion methods. We've already covered how to convert numbers to strings. In this short tutorial, we will explain how to convert strings to numbers in JavaScript.

In many cases, numbers may be stored as strings. For example, the value received from a form element is always a string.

Usually, you can treat JavaScript strings containing numbers (and only numbers) as numbers, and JavaScript will automatically perform string-to-number conversion. However, sometimes you need to extract numbers from strings, or have more control over how you convert.

In this quick tip, we will introduce three ways to convert strings to numbers.

Convert string to number using Number()

The most direct way to convert strings to numbers in JavaScript is to use the built-in

constructor. For example: Number

<code class="language-javascript">const str = "10";
console.log(str); // "10"
console.log(typeof str); // "string"

const number = Number(str);
console.log(number); // 10
console.log(typeof number); // "number"</code>
When recording the value and its type of

in the console, the results are 10 and strings as strings, respectively. After conversion, the results are 10 as numbers and digits, respectively. str

You can view the actual example in the CodePen demonstration below.

[CodePen demo link (please https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)]

Note that if you pass a non-numeric string to a number, NaN will be returned.

Convert strings to numbers using

and parseInt() parseFloat() Another way is to use

and

. As the name implies, parseInt() parses a string into an integer, while parseFloat() parses a string into a number with a decimal point. parseInt() parseFloat()Example:

Similar to the first method, when recording the value and its type of
<code class="language-javascript">const str = "10.9";
console.log(str); // "10.9"
console.log(typeof str); // "string"

const intNumber = parseInt(str);
console.log(intNumber); // 10
console.log(typeof intNumber); // "number"

const floatNumber = parseFloat(str);
console.log(floatNumber); // 10.9
console.log(typeof floatNumber); // "number"</code>
in the console, the results are 10.9 and strings as strings, respectively. However, when parsing

with str, the value of parseInt becomes 10 and its type is a number. str

On the other hand, when parsing parseFloat with str, the value of floatNumber becomes 10.9 (as a number), and its type is a number.

You can view the actual example in the CodePen demonstration below.

[CodePen demo link (please https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)]

The second parameter of

parseInt()

Accepts the second parameter that specifies the cardinality of the number to be parsed from the string. This parameter is actually optional, but it is highly recommended that you always provide it. parseInt()

If there is no such second parameter,

will perform automatic cardinality detection. That is, it detects the cardinality of numbers through the format in the string. Numbers starting with 0x or 0X are considered hexadecimal (base 16), and all other numbers are considered decimal. parseInt

So, for example, if you are calling

, the input value will be treated as an octal number; but 8 is not an octal number (because the octal number is 0-7), so the function will return zero, not eight. parseInt("08")

To avoid any confusion, always specify the cardinality when using

. parseInt()

Convert string to number using a one-yuan plus sign

The third way to convert a string to a number is to use the one-yuan plus sign ( ). If the operand is used before the unary plus sign, it will try to convert it to a number. So, if the operand is a string containing a number, the unary plus sign will convert it to a number.

Example:

<code class="language-javascript">const str = "10";
console.log(str); // "10"
console.log(typeof str); // "string"

const number = Number(str);
console.log(number); // 10
console.log(typeof number); // "number"</code>
When you record the type of

, it is a string as expected. However, when you record the value of str and its type, 10 and digits are recorded in the console respectively. str

You can view the actual example in the CodePen demonstration below.

[CodePen demo link (please https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)]

How to deal with non-numeric characters in strings

Be sure to consider the case where strings may contain characters other than numbers, and how each approach deals with this situation.

When using

, if the string contains characters other than numbers, plus ( ) and minus (-) at the beginning, or decimal points, the return value is the special value NaN (non-number). NaN is a global attribute that represents a non-numeric one. When the operands or parameters of these operations are not numbers or cannot be used for that particular mathematical operation, some numerical operations will return it. Number()

On the other hand, if the number is at the beginning of the string,

and parseInt() will parse the string. It discards the remaining characters and takes the number encountered at the beginning of the string. However, if the string begins with a character other than a number, a plus ( ) and a minus (-) at the beginning, or a decimal point, the return value is the special value NaN (non-number). parseFloat()

You can view the actual example in the CodePen demonstration below.

[CodePen demo link (please https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)]

As you can see, Number() returns NaN because the string contains px. However, parseInt() returns 10 because it is at the beginning of the string.

You can use the global function isNaN() to check if the value is NaN.

Conclusion

This short tutorial introduces three ways to convert strings to numbers in JavaScript. Number() You can convert strings to numbers, whether they are floating point numbers or integers. However, if the string contains other characters, it returns NaN. This will be useful if you want to ensure strict conversion of strings.

On the other hand, parseInt() and parseFloat() are more flexible in dealing with other characters in numbers. However, in some cases, the two functions cannot be used interchangeably. For example, if the number in the string is a floating point number and you use parseInt(), you will get an incorrect value compared to the string.

While the one-yuan plus sign is easy to use, it may reduce the readability of the code. No matter which method you choose, be sure to note that the return result may be NaN.

If you find this article useful, you may also like the following:

  • Learn to use JavaScript programming
  • How to learn JavaScript quickly: Six simple thinking tips (https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)
  • 25 JavaScript abbreviation coding skills (https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)
  • ES6 Practical Practice: New Digital Method (https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)
  • ES6 Practical Practice: New String Method — String.prototype.* (https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)
  • True and false values: Not everything in JavaScript is equal (https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)

FAQs on converting strings to numbers in JavaScript

What are the different ways to convert strings to numbers in JavaScript?

There are several ways to convert strings to numbers in JavaScript. The most commonly used methods include Number() functions, parseInt() functions, parseFloat() functions, and unary plus sign ( ) operators. Each method has its own purpose and can be used according to the specific requirements of the code.

Number() How do functions work in JavaScript?

The Number() function in JavaScript can be used to convert strings to numbers. It takes a string as an argument and returns a number. If the string cannot be converted to a number, NaN (non-number) is returned. For example, Number("1234") will return 1234, while Number("1234abc") will return NaN.

What is the difference between

parseInt() and parseFloat() in JavaScript?

parseInt() and parseFloat() are both used to convert strings to numbers in JavaScript. The difference is the type of numeric they return. parseInt() returns an integer, while parseFloat() returns a floating point number. For example, parseInt("123.45") will return 123, while parseFloat("123.45") will return 123.45.

How to use the unary plus sign ( ) operator to convert a string to a number in JavaScript?

The unary plus sign ( ) operator can be used to convert a string to a number in JavaScript. It is placed before the string as follows: "1234". This will return the number 1234. If the string cannot be converted to a number, NaN is returned.

What happens if I try to convert a non-numeric string to a number in JavaScript?

If you try to convert a non-numeric string to a number in JavaScript using any of the above methods, it will return NaN, i.e. non-numeric.

How to check whether the conversion from string to number in JavaScript is successful?

You can use the isNaN() function in JavaScript to check whether the conversion from a string to a number is successful. If the parameter is non-number (NaN), this function returns true, otherwise false.

Can I convert a string to a number in JavaScript without using any built-in functions?

Yes, strings can be converted to numbers in JavaScript without using any built-in functions, although this is more complex and is not recommended for beginners. One way is to iterate over each character in the string using a loop and calculate the number using the ASCII value of the number.

How to convert a string to an integer in JavaScript?

You can use the parseInt() function to convert a string to an integer in JavaScript. This function takes a string as an argument and returns an integer. If the string cannot be converted to an integer, NaN is returned.

How to convert a string to a floating point number in JavaScript?

You can use the parseFloat() function to convert a string to a floating point number in JavaScript. This function takes a string as an argument and returns a floating point number. If the string cannot be converted to a floating point number, NaN is returned.

What is the best way to convert a string to a number in JavaScript?

The best way to convert a string to a number in JavaScript depends on your specific requirements. If you need integers, use parseInt(). If you need floating point numbers, use parseFloat(). If you are not sure, use the Number() function or the unary plus sign ( ) operator, as they can handle integers and floating point numbers.

Please note that I have tried my best to pseudo-originalize the original text and preserve the original format and location of the image. Since I cannot access external websites and image links, I cannot verify the validity of image links. Please confirm by yourself. If necessary, please provide the local file of the image.

The above is the detailed content of Quick Tip: How to Convert a String to a Number in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn