Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String object to number Typescript

Lets say, I have a string like "150 test". How can I convert this string to a number with the value of 150?

Thanks

like image 714
hindi1991 Avatar asked Oct 18 '25 06:10

hindi1991


1 Answers

Typescript supports type casting, which you will need in your case if you have your variable types declared.

You simply just want to achieve something like this in JS.

var result = parseInt("125 test");
// result is 125

So, it's possible to cast like follows in typescript,

let msg: String = "125 test";

// If 'msg' is 'String', cast it to 'string' since 'parseInt' argument only accepts 'string'.
let result: Number = parseInt(<string>msg);
// result is 125

This will then be transpiled into js, like;

var msg = "125 test";
var result = parseInt(msg);
like image 52
choz Avatar answered Oct 21 '25 09:10

choz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!