开发者

Javascript String to Number type coercion

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开发者_如何学JAVA 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 valid String representation of a floating pointer number. I would have expected parseInt to have failed as well.

Edit: However, as opposed to type casting the value, parseInt is 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]), the toNumber function is used to perform the conversion -- described in section 9.3.1. The behavior of parseInt is described in section 15.1.2.2.


5.0.1 is not a number. 5.01 is a number. It works with parseInt because parseInt is ignoring everything after the first decimal.


("5.0.1" > 4) -> (Number("5.0.1") > 4) -> (NaN > 4) -> false.


It will start ignoring when an invalid string appears, but will try to parse the first part.

parseInt("23.2332adsasd") -> 23
parseFloat("23.23adsdsd") -> 23.23


Object.prototype.toNumber=function(){return this-0;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜