Why in this situation when i want to convert string to number parseInt() works but Number() not?
parseInt(this.element.style.left) << it works
Number(this.element.style.left) << it doesn't, there is NaN
Why in this situation when i want to convert string to number parseInt() works but Number() not?
parseInt(this.element.style.left) << it works
Number(this.element.style.left) << it doesn't, there is NaN
With parseInt:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
In contrast, Number
tries to parse the entire argument as a number.
With style.left
ending in px
, for example, parseInt('12px')
works because the px
can just be ignored by the parseInt
. But Number('12px')
doesn't work because all the characters of the '12px'
cannot be interpreted as a number.
parseInt
skips invalid characters (and stops parsing there), evaluating to what's been parsed so far.
Number
fails to parse at all when there are any invalid characters anywhere.