Converting Strings to Numbers with parseInt() and Number()
When converting strings to numbers in JavaScript, two commonly used functions are parseInt() and Number(). While they both share the purpose of numerical conversion, they differ in their approach and behavior.
parseInt()
parseInt() performs a more specific task known as parsing. It attempts to extract a whole number from a string. When parsing, parseInt() reads the string from left to right, stopping at the first non-digit character. Any subsequent characters in the string are ignored.
parseInt() also takes an optional second argument, the radix or base, which specifies the number system used to interpret the digits. The default radix is 10 (decimal), but it can be set to any integer between 2 and 36.
Examples:
parseInt("20px"); // 20 parseInt("10100", 2); // 20 (binary) parseInt("2e1"); // 2 (does not parse the "e1")
Number()
Number(), on the other hand, is a constructor function that converts a string to a number, performing type conversion. Unlike parseInt(), Number() attempts to convert the entire string to a number, even if it contains non-numeric characters.
If the string contains non-numeric characters, Number() will return NaN (Not-a-Number). However, it has some notable behaviors in specific cases:
Examples:
Number("20px"); // NaN Number("2e1"); // 20 Number("010"); // 10 Number("0o10"); // 8 Number("0xF"); // 15
Additional Considerations
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