The best answers to the question “How to convert a string to number in TypeScript?” in the category Dev.
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`? */;
The Typescript way to do this would be:
Number('1234') // 1234 Number('9BX9') // NaN
as answered here: https://stackoverflow.com/a/23440948/2083492
parseFloat functions, or simply use the unary
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
Table taken from this answer
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, 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
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
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.
The fact that code gets clearer is a nice side effect of specifying the radix parameter.
parseFloat only parses numeric expressions in radix 10, there’s no need for a radix parameter here.
- Why do we need to use radix? (SO Question)
- SO Answer to “What is the difference between parseInt() and Number()?”
For our fellow Angular users:
Within a template,
parseInt(x) throws an error, and
+x has no effect. Valid casting will be