TypeScript cast of string to number
Posted on: 2015-05-05
The simple task of casting from a primitive type to another can be sometimes easier than we think. If you come from C# you may search within TypeScript the Convert.ToInt32()
or Int32.Parse()
or maybe just use int
. None of these conversion syntaxes works with TypeScript. To cast a string to a number, you have to use JavaScript. This means that you can either use the parseInt
function or to simply add a plus sign in from of your string.
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).