"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 > When to Use parseInt() and Number() for String to Number Conversion in JavaScript?

When to Use parseInt() and Number() for String to Number Conversion in JavaScript?

Published on 2024-11-17
Browse:780

 When to Use parseInt() and Number() for String to Number Conversion in JavaScript?

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:

  • It can handle exponential notation (e.g., "2e1") and convert it to a number.
  • It can detect and parse implicit octal notations (e.g., "010"), but it can also be used to explicitly convert to octal using "0o".
  • It can handle hexadecimal numbers prefixed with "0x".

Examples:

Number("20px");       // NaN
Number("2e1");        // 20
Number("010");         // 10
Number("0o10");         // 8
Number("0xF");   // 15

Additional Considerations

  • parseInt() is generally preferred when you need to parse a string as a whole number, while Number() is more suitable for converting values to numeric types.
  • The unary plus operator ( ) can also be used to convert a string to a number, which is equivalent to using the Number() constructor.
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