"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > parseInt() vs. Number(): How Do They Differ in String-to-Number Conversion?

parseInt() vs. Number(): How Do They Differ in String-to-Number Conversion?

Published on 2024-11-20
Browse:767

parseInt() vs. Number(): How Do They Differ in String-to-Number Conversion?

Understanding the Nuances of parseInt() and Number() in String-to-Number Conversion

When dealing with string-to-number conversion in JavaScript, it's essential to grasp the differences between parseInt() and Number(). These two methods exhibit distinct behaviors in handling string inputs.

Semantic Differences: Parsing vs. Type Conversion

parseInt() performs parsing, which means it interprets a portion of the string as a number, while ignoring any trailing characters that don't fit the designated numeral system. Number(), on the other hand, performs type conversion, attempting to convert the entire string into a numeric value.

Examples:

// Parsing
parseInt("20px");       // 20
parseInt("10100", 2);   // 20
parseInt("2e1");        // 2

// Type conversion
Number("20px");       // NaN
Number("2e1");        // 20 (exponential notation)

Trailing Characters and Implicit Octals

parseInt() disregards trailing characters that don't correspond to numeric digits in the specified base. The Number() constructor, however, doesn't detect implicit octals (numbers prefixed with a 0, representing an octal numeral system). Explicit octal notation (0o) is recognized by Number().

// Implicit octal detection
Number("010");         // 10
Number("0o10")         // 8

// Parsed as octal by default
parseInt("010");       // 8
parseInt("010", 10);   // 10 (force decimal radix)

Hexadecimal Notation and Unary Plus Operator

Both parseInt() and Number() can handle hexadecimal notation, numbers represented with a leading 0x prefix. Additionally, the Unary Plus Operator ( ) can also be used to perform numeric type conversion, equivalent to using the Number() constructor.

// Hexadecimal notation
Number("0xF");   // 15
parseInt("0xF"); //15

// Unary Plus Operator
 "2e1";   // 20
 "0xF";   // 15
 "010";   // 10

By understanding the specific characteristics of parseInt() and Number(), developers can make informed decisions when converting strings to numbers in JavaScript, ensuring accurate and reliable results.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3