Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between parseInt(string) and Number(string) in JavaScript?
In JavaScript, parseInt() and Number() both convert strings to numbers, but they handle invalid characters differently. Understanding their behavior is crucial for proper string-to-number conversion.
parseInt() Method
The parseInt() method parses a string character by character and stops at the first non-digit character, returning the parsed integer portion.
console.log(parseInt("765world"));
console.log(parseInt("50px"));
console.log(parseInt("123.45"));
console.log(parseInt("abc123"));
765 50 123 NaN
Number() Method
Number() attempts to convert the entire string to a number. If any part of the string is invalid, it returns NaN.
console.log(Number("765world"));
console.log(Number("50px"));
console.log(Number("123.45"));
console.log(Number("123"));
NaN NaN 123.45 123
Key Differences
// parseInt stops at first non-digit
console.log(parseInt("42abc")); // 42
console.log(Number("42abc")); // NaN
// Number handles decimals, parseInt ignores them
console.log(parseInt("42.99")); // 42
console.log(Number("42.99")); // 42.99
// Both handle whitespace
console.log(parseInt(" 42 ")); // 42
console.log(Number(" 42 ")); // 42
42 NaN 42 42.99 42 42
Comparison
| Feature | parseInt() | Number() |
|---|---|---|
| Partial parsing | Yes - stops at first invalid character | No - entire string must be valid |
| Decimal handling | Ignores decimal part | Preserves decimal values |
| Return type | Integer only | Integer or float |
| Empty string | NaN | 0 |
Common Use Cases
// Use parseInt for extracting numbers from mixed strings
let width = parseInt("300px");
console.log("Width:", width);
// Use Number for strict conversion
let price = Number("29.99");
console.log("Price:", price);
// parseInt with radix for different number systems
console.log("Binary:", parseInt("1010", 2));
console.log("Hexadecimal:", parseInt("FF", 16));
Width: 300 Price: 29.99 Binary: 10 Hexadecimal: 255
Conclusion
Use parseInt() when you need to extract integers from mixed strings, and Number() when you require strict conversion of the entire string to a number, including decimals.
Advertisements
