Wednesday, May 22, 2019

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.


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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...