In TypeScript, converting a string to a number is a piece of cake! There are a few different ways to do it, so let’s walk through them with some examples.
Example
Using the ‘+’ Unary Operator
let str: string = "431";
console.log(typeof str);
let num = +str;
console.log(typeof num);
Using the Number()
Method
let str: string = "431";
console.log(typeof str);
let num = Number(str);
console.log(typeof num);
Handling Different Types of Numbers
Numbers can be either floating-point (float) or integer (int). We use different methods to convert them.
let str1: string = "102.2";
console.log(typeof str1);
//"string"
let num1 = parseFloat(str1);
console.log(`${num1}` + " is of type: " + typeof num1);
// "102.2 is of type: number"
let str2: string = "61";
console.log(typeof str2);
//"string"
let num2 = parseInt(str2);
console.log(`${num2}` + " is of type: " + typeof num2);
//"61 is of type: number"
See? Converting strings to numbers in TypeScript is as easy as pie! Whether you prefer using the unary operator, the Number()
method, or parseInt()
and parseFloat()
functions, TypeScript has got you covered. So go ahead, convert those strings and crunch those numbers!
People also love to read about TypeScript Partial Type and TypeScript Unknown Type or TypeScript Optional Parameters with our comprehensive guides – dive into these insightful blogs to enhance your knowledge and proficiency.
Leave a Reply