4

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

Thanks

0

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Adding type declarations to variables which are immediately assigned is unnecessary, because typescript automatically add the type to the variable under the hood.
Using box types like String and Number is bad practice. Check out typescript official do's and don'ts: typescriptlang.org/docs/handbook/declaration-files/…
@BalázsTakács That's not the case here. Editors or linters are picky about the type definitions in typescript. At least I show him how he can handle them
Actually, that is considered bad practice because of the case like parseInt above. If OP in fact develops his own codebase with typescript and use boxed types, I don't see why not.
5

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

Comments

3

Use numbers parseInt method.

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

Comments

0

you can use this code snippet:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.