How to convert a string to number in TypeScript?

1.7k2013 年提問 · Paul0515 ·javascripttypescript 主題:其他 → 在 Stack Overflow 看原文 ↗

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`? */;

重點答案

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

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

All of the mentioned techniques 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).

Conversion table Table taken from this answer

For our fellow Angular users:

Within a template, Number(x) and parseInt(x) throws an error, and +x has no effect. Valid casting will be x*1 or x/1.