Given a string representation of a number, how can I convert it to number type in TypeScript? var numberString: string = "1234"; var numberValue: number = /* what should I do with `numberString`? */;

You can convert a string representation of a number to a number type in TypeScript using the parseInt() or parseFloat() functions. Here's how you can do it:

typescript

var numberString: string = "1234";
var numberValue: number = parseInt(numberString);  // Using parseInt()

console.log(numberValue);  // Output: 1234

In the above example, the parseInt() function is used to convert the string "1234" to the number 1234. If you want to handle floating-point numbers, you can use parseFloat():

typescript

var floatString: string = "3.14";
var floatValue: number = parseFloat(floatString);  // Using parseFloat()

console.log(floatValue);  // Output: 3.14

Both parseInt() and parseFloat() functions parse the string and return the corresponding number. Keep in mind that if the string cannot be parsed as a valid number, the result will be NaN (Not-a-Number). Also, note that parseInt() will only return integer values, and parseFloat() will handle floating-point numbers.

Comments