Categories
TypeScript Answers

How to convert a string to number in TypeScript?

Spread the love

Sometimes, we want to convert a string to number in TypeScript.

In this article, we’ll look at how to convert a string to number in TypeScript.

How to convert a string to number in TypeScript?

To convert a string to number in TypeScript, we can use the + operator, parseInt or parseFloat functions.

For instance, we write:

const x = "32";
const y: number = +x;

to convert x to a floating point number with +

Or we write

const x = "32";
const y: number = parseInt(x);

to convert x to an integer with parseInt

const x = "32";
const y: number = parseFloat(x);

to convert x to a floating point number with parseFloat

Conclusion

To convert a string to number in TypeScript, we can use the + operator, parseInt or parseFloat functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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