Published on

TypeScript: String to Number

Authors
  • avatar
    Name
    Carlos Baraza
    Twitter
    @carlosbaraza
    Bio
    I write software and other philosophical stuff.

This article is part of my TypeScript series. Please, consider subscribing to my newsletter for tips on programming, entrepreneurship and design.

I have noticed multiple questions regarding how to convert a String value to a Number using TypeScript.

The answer is that you can convert String to Numbers just the same way than JavaScript, using parseInt("42"), parseFloat("42"), +"42" or Number("42").

const numberString: string = "42";

const number: number = parseInt(numberString);
const number: number = parseFloat(numberString);
const number: number = +numberString;
const number: number = Number(numberString);

Multiple approaches return the same number type parsing a string number

This StackOverflow answer compares a multitude of alternative methods:

Finally, consider subscribing to my newsletter or following me on Twitter @carlosbaraza.