Home >Web Front-end >JS Tutorial >Quick Tip: How to Convert a String to a Number in JavaScript
Core points
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. 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. 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.
Number()
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
[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
parseInt()
parseFloat()
Another way is to use . 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 ofparseInt()
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()
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
, 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")
. parseInt()
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
[CodePen demo link (please https://www.php.cn/link/a1d41c14c1d0aa9b9cc1e228d962fe42)]
How to deal with non-numeric characters in strings
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()
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()
[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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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!