Wednesday 22 May 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...