I ran into this issue the other day and couldn’t figure out what exactly is happening under the hood. What are the rules for coercion of a String into a Number type? and why does it fail in the instance of ‘5.0.1’?
var numStr = '5.0';
var floatStr = '5.0.1';
//Passes
if (numStr >= 4) {
alert('5 > 4');
}
//Fails
if (floatStr >= 4) {
alert('5.0.1 > 4');
}
console.log(parseInt(numStr)); //5
console.log(parseInt(floatStr)); //5
console.log(Number(numStr)); //5
console.log(Number(floatStr)); //NaN
Well, for one,
"5.0.1"is not a validStringrepresentation of a floating pointer number. I would have expectedparseIntto have failed as well.Edit: However, as opposed to type casting the value,
parseIntis a function that was designed to extract a value with more tolerance for noise.The particular implementation details are defined in: EMCA-262
For instance, when applying a cast
Number([value]), thetoNumberfunction is used to perform the conversion — described in section 9.3.1. The behavior ofparseIntis described in section 15.1.2.2.