TypeScript Converting a String to a number
Anyone a suggestion on how to convert a string to a number in 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;
checking if a string is numeric is answered here: In Typescript, How to check if a string is Numeric.
您可以使用parseInt
或parseFloat
函数,或者使用一元+
运算符:
var x = "32";
var y = +x; // y: number
The Typescript way to do this would be:
Number('1234') // 1234
Number('9BX9') // NaN
as answered here: https://stackoverflow.com/a/23440948/2083492
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
.
上一篇: Angular 2.0生命周期和Typescript
下一篇: TypeScript将字符串转换为数字