简体   繁体   中英

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

parseInt()

An integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.

You can use parseInt() which will try to parse the string to number until it gets a non-digit character.

 var str = "150 test"; console.log(parseInt(str)) 

使用数字parseInt方法。

 console.log( Number.parseInt('150 test') ); 

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);

you can use this code snippet:

let str = "150 test";
let result = Number(str.split(" ")[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM