Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way of performing an "integer " conversion/typecast in javascript?

Another question asked about the meaning of the code snippet a >>> 0 in Javascript. It turns out that it is a clever way of ensuring that a variable is a unsigned 32-bit integer.

This is pretty neat, but I don't like it for two reasons.

  • The intent of the expression is not clear, at least not to me.
  • It does not work for negative numbers

This leads me to ask: What is the most idiomatic way of converting an arbitrary value to an "integer" in Javascript? It should work for signed integers, not just non-negative numbers. Cases where this breaks due to the fact that integers are just floats in disguise in Javascript are acceptable, but should be acknowledged. It should not return undefined or NaN in any case (these are not integers), but return 0 for non-numeric values.

like image 897
fmark Avatar asked Jun 21 '10 12:06

fmark


People also ask

What is typecasting in JavaScript?

Type conversion (or typecasting) means transfer of data from one data type to another. Implicit conversion happens when the compiler (for compiled languages) or runtime (for script languages like JavaScript) automatically converts data types. The source code can also explicitly require a conversion to take place.

How do you convert a string to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.


1 Answers

parseInt is the “most idiomatic” way, as it exactly describes what you want it to do. The drawback of parseInt is that it return NaN if you input a non-numeric string.

Another method is bitwise ORing by 0 (| 0), which also works for negative numbers. Moreover, it returns 0 when using it on a non-numeric string. Another advantage is that it is a bit faster than parseInt when using it on real numbers; it is slower when feeding it strings.

  • 12.4 | 0 outputs 12
  • -12.4 | 0 outputs -12
  • "12.4" | 0 outputs 12
  • "not a number" | 0 outputs 0
like image 158
Marcel Korpel Avatar answered Oct 22 '22 13:10

Marcel Korpel