How to convert a string to number in typescript?
In this article, we will discuss how we can convert a string to a number in typescript by using various methods and examples.
we can convert a string to a number in Typescript by using the following methods:
- using Unary Plus (+) operator
- parseInt( ) function
- parseFloat( ) function
- Global number( ) function
convert string by using unary operator
In this code, we will convert string to number by using the '+'
Unary Operator.
a unary operator will convert all the strings representing of numbers like '123', True, False, etc into numbers. for True it will convert it into 1 and for false it will be 0.
let str = "540";
console.log('type of str before converting:',typeof str);
let num = +str;
console.log('after converting str becomes:',typeof num);
console.log(num);
console.log(+true);
console.log(+false);
type of str before converting: string after converting str becomes: number 540 1 0
Convert string into number using parseInt( ) function
parseInt( )
function will convert string representing number into integer form.
let str = "540";
console.log('before converting type:', typeof str);
let num = parseInt(str);
console.log('after converting type:', typeof num);
before converting type: string after converting type: number
Convert string into number using parseFloat( ) function
if the string contains a floating point value then use parseFloat() instead of parseInt().
parseFloat( )
function will convert string representing floating point number into float number.
let str = "540.5";
console.log('before converting type:', typeof str);
let num = parseFloat(str);
console.log('after converting type:', typeof num);
console.log(num)
before converting type: string after converting type: number 540.5
Converting strings into numbers using the Number( ) function
Number()
function is one of the best functions for converting strings into numbers. it is like + unary operator.
let str = "540.5";
console.log('before converting type:', typeof str);
let num = Number(str);
console.log('after converting type:', typeof num);
console.log(num)
console.log(Number(true))
console.log(Number(false))
console.log(Number("40"))
console.log(Number("50.5"))
before converting type: string after converting type: number 540.5 1 0 40 50.5