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
How to convert a string to a number in JavaScript using the unary plus operator ( + ) The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number.
To explicitly coerce a value to a string in JavaScript we can use the String() function. To implicitly coerce a value to a string, we can use the + operator with any operand that is a string. We should be careful when using type coercion when we want to create an operation and one of our operand types is a string.
Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.
Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.
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.
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