Tuesday, July 17, 2018

Typescript Number to String or String to Number conversion examples

Typescript primitive data type conversion

Number and String are basic primitive data types in typescript programming language. The number to String and String to Number conversion are one of the simple tasks of typescript developers. For conversion to number, String must contain only numbers.

The number to String conversion examples.

We can do many ways to achieve this.

1 Append with an empty string.
2. toString() method
3. using string() method

Append with an empty string.

number values are 11,13.  add an empty string to Number value returns a string object typeof method checks value type and returns primitive type as a string

var a: number = 12
var str: string = a + '';
console.log(typeof (a)) // outpus number  as output
console.log(typeof (str)) // outpus string as output
console.log(str) //outputs 12 as string value

var a: number = null
var str: string = a + '';
console.log(typeof (str)) // outpus string as output
console.log(str) //outputs null in the form of string

var a: number = undefined
var str: string = a + '';
console.log(typeof (str)) // outpus string as output
console.log(str) //outputs undefined in the form of string

toString() method

calling toString() method  on any data types returns string object

var a: number = 17
var str: string = a .toString()
console.log(typeof (str)) // outpus string as output
console.log(a) //outputs 12 as string value

if we use null and undefined with toString() method, compiler through 'Cannot read property 'toString' of null' error

string() method

this is the easiest way of a convert to string method

var a: number = 12
var stringValue = String(a);
console.log(typeof(stringValue) // outpus string  as output

String to Number example 

This conversion can be achieved using various approaches

1. parseInt
2. parseFloat
3. Number()

parseInt() and parseFloat() method

parseInt and parseFloat methods take input number in the form of a string and return number

console.log(parseInt('32', 10)) // outpus 32 as output
console.log(parseInt('45')) // outpus 45 as outpu
console.log(parseInt('45abc')) // outpus 45 as output
console.log(parseInt('null')) // outpus NaN as output

console.log(parseFloat('32.32')) // outpus 32.32 as output
console.log(parseInt('45')) // outpus 45 as output

Number() method

Number() constructor takes a string as a parameter and returns number as output

console.log(Number('12')) // outpus 12 as output
console.log(Number('null')) // outpus NaN as output
console.log(Number('undefined')) // outpus NaN as output

This is understanding on primitive types conversion in typescript language.




Related article


EmoticonEmoticon