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.
Answer
You can use the parseInt
or parseFloat
functions, or simply use the unary +
operator:
var x = "32";
var y = +x; // y: number
No comments:
Post a Comment