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;
A unary operator is an operator used to operate on a single operand to return a new value. In other words, it is an operator that updates the value of an operand or expression's value by using the appropriate unary operators. In Unary Operator, operators have equal priority from right to left side associativity.
Be careful when checking against NaN (the operator ===
and !==
don't work as expected with NaN
). Use:
isNaN(+maybeNumber) // returns true if NaN, otherwise false
function isNumber(value: string | number): boolean
{
return ((value != null) &&
(value !== '') &&
!isNaN(Number(value.toString())));
}
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