Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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
like image 710
Chestone Avatar asked Jul 15 '11 20:07

Chestone


People also ask

How do you convert a string to a number in JavaScript?

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.

How do you use type coercion in JavaScript?

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.

What is type conversion and coercion in JavaScript?

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.

Why does JavaScript do type coercion?

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.


3 Answers

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.

like image 103
Peter Avatar answered Oct 01 '22 13:10

Peter


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.

like image 39
Craig M Avatar answered Oct 01 '22 13:10

Craig M


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

like image 24
Neil Avatar answered Oct 01 '22 11:10

Neil