Home > Web Front-end > JS Tutorial > How to convert string to number in js

How to convert string to number in js

下次还敢
Release: 2024-05-06 09:30:28
Original
961 people have browsed it

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 string to number in js

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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, the

Number() 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template