本文翻译自:TypeScript Converting a String to a number
Anyone a suggestion on how to convert a string to a number in TypeScript? 有人建议如何将字符串转换为TypeScript中的数字?
var aNumber : number = "1"; // --> Error
// Could this be done?
var defaultValue = 0;
var aNumber : number = "1".toInt32(defaultValue);
// Or ..
var defaultValue = 0;
var aNumber : number = StringToInt("1", defaultValue);
Update: I did some extra puzzling, the best sofar I've come up with: var aNumber : number = ( "1") * 1; 更新:我做了一些额外的困惑,我想出的最好的音乐:var aNumber:number =(“1”)* 1;
checking if a string is numeric is answered here: In Typescript, How to check if a string is Numeric . 检查字符串是否为数字在此处回答: 在Typescript中,如何检查字符串是否为数字 。
#1楼
参考:https://stackoom.com/question/zXk1/TypeScript将字符串转换为数字
#2楼
You can use the parseInt
or parseFloat
functions, or simply use the unary +
operator: 您可以使用parseInt
或parseFloat
函数,或者只使用一元+
运算符:
var x = "32";
var y = +x; // y: number
#3楼
Expounding on what Ryan said, TypeScript embraces the JavaScript idioms in general. 在谈到Ryan所说的内容时,TypeScript总体上包含了JavaScript习惯用法。
var n = +"1"; // the unary + converts to number
var b = !!"2"; // the !! converts truthy to true, and falsy to false
var s = ""+3; // the ""+ converts to string via toString()
All the interesting in-depth details at JavaScript Type Conversion . JavaScript类型转换中所有有趣的深入细节。
#4楼
The Typescript way to do this would be: Typescript的方法是:
Number('1234') // 1234
Number('9BX9') // NaN
as answered here: https://stackoverflow.com/a/23440948/2083492 在这里回答: https : //stackoverflow.com/a/23440948/2083492
#5楼
For our fellow Angular users: 对于我们的Angular用户:
Within a template , Number(x)
and parseInt(x)
throws an error, and +x
has no effect. 在模板中 , Number(x)
和parseInt(x)
抛出错误, +x
无效。 Valid casting will be x*1
or x/1
. 有效的强制转换为x*1
或x/1
。
#6楼
在Typescript中有内置函数,如parseInt()
, parseFloat()
和Number()
,你可以使用它们。