Monday, July 16, 2018

javascript integer to string Conversion example

Learn String to integer conversion tutorial with examples

Convert String to integer  examples
In my previous article, Learned how to do String to Integer conversion. Now we will walk through the Integer to String conversion in javascript. This is a basic example tutorial from Number to String conversion where numbers can be integer and float values conversion of integer to string is common and basic tasks for web developers.

We have different approaches to convert to String object This article explains the different approaches to achieve it.

  • String function declaration
  • Append empty string 
  • using toString() method

String function syntax

String(number)

String function accepts any primitive value as a parameter which returns primitive value. if the integer value is supplied as input, and output integer. This internally calls toString method to convert to String. Please note that String function and String constructor. String construction is created using new String() syntax which returns object. Please see below examples for more understanding

var stringType =  String(51);//  String function returns String data type
var objectDataType = new  String(51);// String constructor returns Object data type
var numbertype =  String(51);// valid and returns 51 as number not string
var undefinedString = String(undefined) // valid and returns "undefined" as string
var nullString = String(null) // valid and returns "null" as string
var numbertype = String(true) // valid and returns "true" as string

Append an empty string to number using plus operator.

 any primitive value type can be converted to string object by appending an empty string.  This conversion process is less illustrative.

var stringNumber =undefined +''     // valid and returns undefined as string type
var stringNumber =null +''     // valid and returns null as string type
var stringNumber =12 +''     // valid and returns 12 as string
var stringNumber =''+43     // valid and returns 43 as string

Using toString() function

The above two approaches internally call toString() method. Any primitive value can be converted to String using this approach.

var number1=123;
var number2=null;
var number3=undefined
number1.toString() //valid and returns "123" as string type
number2.toString() //Not Valid gives compile error like Cannot read property 'toString' of null
number3.toString() //Not Valid gives compile error like Cannot read property 'toString' of undefined

the exception "Cannot read property 'toString' of undefined/null" solved by not calling toString() method for null and undefined values

Related article


EmoticonEmoticon