且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 TypeScript 中将字符串转换为数字?

更新时间:2023-02-19 13:10:46

表格取自 这个答案

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).

Table taken from this answer