Home >Web Front-end >JS Tutorial >How to convert string to number in js
JavaScript provides the following methods to convert strings into numbers: Number() function parses strings into numbers, and returns NaN if it cannot be parsed. The parseInt() function parses strings into integers, ignoring non-numeric prefixes. The parseFloat() function parses a string into a floating point number and accepts strings containing decimal points. The operator is like the Number() function, but treats spaces as 0.
How to convert strings into numbers in JavaScript
JavaScript provides a variety of methods to convert strings For numbers:
1. Number() function
Number()
The function parses the value in the string into a number. If the string cannot be parsed as a number, it will return NaN
(not a number):
<code class="javascript">const num = Number("123"); // 123 const num2 = Number("123abc"); // NaN</code>
2. parseInt() function
parseInt()
Function parses a string into an integer (base 10). If there are non-numeric characters in front of the string, it will ignore them and parse the remaining string:
<code class="javascript">const num = parseInt("123abc"); // 123 const num2 = parseInt("0110"); // 110 (八进制)</code>
3. parseFloat() function
parseFloat ()
Function parses a string into a floating point number. It is similar to parseInt()
, but accepts strings containing decimal points:
<code class="javascript">const num = parseFloat("123.45"); // 123.45 const num2 = parseFloat("0.110"); // 0.11</code>
4. Operator
Unigram # The ## operator can also convert strings to numbers. It is similar to the
Number() function, but treats space characters in the string as 0:
<code class="javascript">const num = +"123"; // 123 const num2 = +" 123 "; // 123</code>
Choose the best method
Which method to use depends on the type of data in the string and the desired result. For numeric strings with no non-numeric characters, theNumber() function is the simplest option. If the string contains non-numeric characters or you need to control the radix,
parseInt() or
parseFloat() is more appropriate.
The above is the detailed content of How to convert string to number in js. For more information, please follow other related articles on the PHP Chinese website!