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.
The above is the detailed content of parseInt() vs. Number(): How Do They Differ in String-to-Number Conversion?. For more information, please follow other related articles on the PHP Chinese website!