TypeScript cast of string to number

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:

(The number of value if the myStringVariable is a proper number)

If the value are not a proper number, the result will be:

NaN OR something else

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).

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

4 thoughts on “TypeScript cast of string to number

  1. It would be nice if you show the outcome of the 4 examples you list with numbers and non-numbers because I read elsewhere parseInt will return NaN if it’s not a number but using + will return 0.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.