Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to number in TypeScript?

Tags:

typescript

Given a string representation of a number, how can I convert it to number type in TypeScript?

var numberString: string = "1234"; var numberValue: number = /* what should I do with `numberString`? */; 
like image 511
Paul0515 Avatar asked Feb 02 '13 23:02

Paul0515


People also ask

How do I convert objects to numbers in TypeScript?

You can use parseInt() which will try to parse the string to number until it gets a non-digit character. Show activity on this post. Use numbers parseInt method.

How do I convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.


1 Answers

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

var x = "32"; var y: number = +x; 

All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123", but will behave differently for various other, possibly expected, cases (like "123.45") and corner cases (like null).

Conversion table Table taken from this answer

like image 124
Ryan Cavanaugh Avatar answered Sep 24 '22 06:09

Ryan Cavanaugh