I have gone through similar questions and answers on StackOverflow and found this:
parseInt("123hui")
returns 123
Number("123hui")
returns NaN
As, parseInt()
parses up to the first non-digit and returns whatever it had parsed and Number()
tries to convert the entire string into a number, why unlikely behaviour in case of parseInt('')
and Number('')
.
I feel ideally parseInt
should return NaN
just like it does with Number("123hui")
Now my next question:
As 0 == ''
returns true
I believe it interprets like 0 == Number('')
which is true. So does the compiler really treat it like 0 == Number('')
and not like 0 == parseInt('')
or am I missing some points?
If the first character cannot be converted to a number with the radix in use, parseInt returns NaN . Leading whitespace is allowed. For arithmetic purposes, the NaN value is not a number in any radix. You can call the Number.isNaN function to determine if the result of parseInt is NaN .
parseInt() method parses a string argument and returns an integer of the specified radix or base.
Try replacing your return with return decimalnum; -- you may still be returning undefined. parseInt is not for rounding - it actually takes the integer component of a number, or coerces a string to be a number. If you want to round, use Math.
The difference is due in part to Number()
making use of additional logic for type coercion. Included in the rules it follows for that is:
- A StringNumericLiteral that is empty or contains only white space is converted to +0.
Whereas parseInt()
is defined to simply find and evaluate numeric characters in the input, based on the given or detected radix
. And, it was defined to expect at least one valid character.
13) If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.
14) If Z is empty, return NaN.
Note: 'S' is the input string after any leading whitespace is removed.
As
0==''
returnstrue
I believe it interprets like0==Number('')
[...]
The rules that ==
uses are defined as Abstract Equality.
And, you're right about the coercion/conversion that's used. The relevant step is #6:
If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With