How to Convert a String to a Number in TypeScript?
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? */;
How do I achieve this typescript string to number conversion?
Hey Saanvi,
Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator to achieve a TypeScript string to number conversion:
var x: string = "32";
var y: number = +x;
The mentioned technique will have correct typing and will correctly parse simple decimal integer strings like “123”, but will behave differently for various other, possibly expected, cases (like “123.45”) and corner cases (like null).
Hey Saanvi,
To convert a TypeScript string to a number, you can use several methods. Here’s an example that demonstrates a few of the most common ways to achieve this:
var numberString: string = "1234";
// Using Number constructor
var numberValue: number = Number(numberString);
// Using parseInt function
var numberValue2: number = parseInt(numberString, 10);
// Using parseFloat function
var numberValue3: number = parseFloat(numberString);
console.log(numberValue); // 1234
console.log(numberValue2); // 1234
console.log(numberValue3); // 1234
In the given TypeScript string to number conversion example, you can use any of these methods to convert numberString to a number type.
Hey Saanvi,
As shown by other answers here, there are multiple ways to achieve a TypeScript string-to-number conversion:
Number('123');
+'123';
parseInt('123');
parseFloat('123.45');
I’d like to mention one more thing about parseInt, though.
When using parseInt, it makes sense to always pass the radix parameter. For decimal conversion, that is 10. This is the default value for the parameter, which is why it can be omitted. For binary, it’s 2 and 16 for hexadecimal. Actually, any radix between and including 2 and 36 works.
parseInt('123'); // 123 (don't do this)
parseInt('123', 10); // 123 (much better)
parseInt('1101', 2); // 13
parseInt('0xfae3', 16); // 64227