Number()
and parseInt()
are two different functions in JavaScript used to convert strings to numbers, and they have some differences in how they handle strings.
Number()
#
- The
Number()
function converts the entire string to a number. - If the string contains non-numeric characters (except leading spaces and signs), it returns
NaN
. - If the string can be fully parsed as a number, it returns that number.
parseInt()
#
- The
parseInt()
function parses the integer part of a string until it encounters the first non-numeric character. - You can specify an optional radix (base) to parse the string.
- If the string starts with a non-numeric character,
parseInt()
returnsNaN
.
Example Explanation#
Example 1#
let a = "1hola1";
console.log(Number(a)); // Output: NaN
console.log(parseInt(a)); // Output: 1
Explanation:
Number("1hola1")
returnsNaN
because the entire string"1hola1"
cannot be converted to a valid number.parseInt("1hola1")
returns1
because it parses from the beginning of the string until it encounters the non-numeric characterh
.
Example 2#
let a = "1";
console.log(Number(a)); // Output: 1
console.log(parseInt(a)); // Output: 1
Explanation:
- Both
Number("1")
andparseInt("1")
return1
because the string"1"
is a valid number without any non-numeric characters interfering with parsing.
Summary#
- Using
Number()
converts the entire string to a number, returningNaN
if the string contains any non-numeric characters. - Using
parseInt()
parses the integer part of the string from the beginning until it encounters a non-numeric character.
Other Examples#
console.log(Number("123.45")); // Output: 123.45
console.log(parseInt("123.45")); // Output: 123
console.log(Number(" 123 ")); // Output: 123
console.log(parseInt(" 123 ")); // Output: 123
console.log(Number("123abc")); // Output: NaN
console.log(parseInt("123abc")); // Output: 123
console.log(Number("abc123")); // Output: NaN
console.log(parseInt("abc123")); // Output: NaN
These examples demonstrate the differences in behavior between Number()
and parseInt()
when handling different strings.
Learned something new again.