Advertisement
Advertisement


How to convert a string to number in TypeScript?


Question

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`? */;
2020/06/01
1
943
6/1/2020 9:30:42 PM

Accepted Answer

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

2020/06/02
1488
6/2/2020 12:40:53 AM


For our fellow Angular users:

Within a template, Number(x) and parseInt(x) throws an error, and +x has no effect. Valid casting will be x*1 or x/1.

2017/07/21

As shown by other answers here, there are multiple ways to do the conversion:

Number('123');
+'123';
parseInt('123');
parseFloat('123.45')

I'd like to mention one more thing on parseInt though.

When using parseInt, it makes sense to always pass the radix parameter. For decimal conversion, that is 10. This is the default value for the parameter, which is why it can be omitted. For binary, it's a 2 and 16 for hexadecimal. Actually, any radix between and including 2 and 36 works.

parseInt('123')         // 123 (don't do this)
parseInt('123', 10)     // 123 (much better)

parseInt('1101', 2)     // 13
parseInt('0xfae3', 16)  // 64227

The parseInt function, well, parses strings to convert them to numbers. In some JS implementations, parseInt parses leading zeros as octal:

Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result. Always specify a radix to avoid this unreliable behavior.

MDN

The fact that code gets clearer is a nice side effect of specifying the radix parameter.

Since parseFloat only parses numeric expressions in radix 10, there's no need for a radix parameter here.

More on this:

2020/06/20

Expounding on what Ryan said, TypeScript embraces the JavaScript idioms in general.

var n = +"1"; // the unary + converts to number
var b = !!"2"; // the !! converts truthy to true, and falsy to false
var s = ""+3; // the ""+ converts to string via toString()

All the interesting in-depth details at JavaScript Type Conversion.

2013/02/05

You can follow either of the following ways.

var str = '54';

var num = +str; //easy way by using + operator
var num = parseInt(str); //by using the parseInt operation 
2017/11/21

String to number conversion:

In Typescript we convert a string to a number in the following ways:

  • ParseInt(): This function takes 2 arguments, the first is a string to parse. The second is the radix (the base in mathematical numeral systems, e.g. 10 for decimal and 2 for binary). It then returns the integer number, if the first character cannot be converted into a number, NaN will be returned.
  • ParseFloat(): Takes as an argument the value which we want to parse, and returns a floating point number. If the value cannot be converted to a number, NaN is returned.
  • + operator: The operator when used appropriately can coerce a string value into a number.

Examples:

/*    parseInt   */

// note that a whole number is returned, so it will round the number
console.log(parseInt('51.023124'));

// parseInt will 'cut off' any part of the string which is not a number
console.log(parseInt('5adfe1234'));

// When the string starts with non number NaN is returned
console.log(parseInt('z123'));

console.log('--------');

/*    parseFloat   */

// parses the string into a number and keeping the precision of the number
console.log(typeof parseFloat('1.12321423'));

// parseFloat will 'cut off' any part of the string which is not a number
console.log(parseFloat('5.5abc'));

console.log('--------');

/*   + operator   */

let myString = '12345'

console.log(typeof +myString);

let myOtherString = '10ab'

// + operator will not cut off any 'non number' string part and will return NaN
console.log(+myOtherString);

Which to use?

  1. Use ParseInt() when you want a string converted to an integer. However, the data type is still a float, since all number values are floating point values in TS. Also use this method when you need to specifiy the radix of the number you want to parse.
  2. Use ParseFloat() when you need to parse a string into a floating point number.
  3. You can use the + operator before a string to coerce it into a floating point number. The advantage of this is that the syntax is very short.
2018/11/03