TypeScript cast of string to number
Posted on: May 5, 2015
var myInt1 = +"123"; var myInt2 = +myStringVariable; var myInt3 = parseInt("123", 10); var myInt4 = Number("123")
The output of the variables if they are proper number are:
123 (The number of value if the myStringVariable is a proper number) 123 123
If the value are not a proper number, the result will be:
NaN NaN NaN OR something else Nan
The parseInt can be deceiving. For example, if you try with "123asd" you will get 12 as an answer. However, if you parse "asd" you will get NaN. I recommend using the function Number when the base is 10 and to relies on parseInt only if you are working with another base (hex for example).