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()
andparseFloat()
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 theparseInt()
andparseFloat()
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
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"
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
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
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"
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()
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:
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"
, 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
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()
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.
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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
