Wednesday, September 12, 2018

JavaScript - Built in Functions - parseInt - toString - toFixed

Built In Methods covered:

  1. parseInt()
  2. toString()
  3. toFixed()

There are some other useful built in functions which allow you to transform values. Consider the following code snippet:

var myNum = "25";
console.log(myNum+" is a "+typeof(myNum));

Console Output:
"25 is a string"

Now, we can use the parseInt method - which is available on the window object. That is, parseInt is available on the Global Scope.

var myNum = "25";
console.log(parseInt(myNum)+" is a "+typeof(parseInt(myNum)));

Console Output:
"25 is a number"

Now, let me try with a string which is not a number:

var myNum = "fdfdf";
console.log(parseInt(myNum)+" is a "+typeof(parseInt(myNum)));

Console Output:
"NaN is a number"


parseInt takes another argument optionally. Here I can specify the base digits of system I am operating.  The default is the decimal system, But, I can change it to hexadecimal system.  For example:

var myNum = "fbb23";
console.log(parseInt(myNum,16)+" is a "+typeof(parseInt(myNum)));

And, now if I hit run:

"1030947 is a number"

JavaScript has transformed from Hexadecimal system to Decimal System.

var myNum = 123;
var myNumStr = myNum.toString();
console.log(myNum+ " is now a "+typeof(myNumStr));

Console Output:
"123 is now a string"

toString is a method defined on the Object.prototype. This is the base prototype of all the objects. Therefore every object has by default has this toString() method. We can apply this on any object in JavaScript.

var myNum = 10.3;
var myNumFixed = myNum.toFixed();
console.log(myNumFixed+ " is now a "+typeof(myNumFixed));

Console Output:
"10 is now a string"

We can also specify the number of decimal places

var myNum = 3.1425;
var myNumFixed = myNum.toFixed(2);
console.log(myNumFixed+ " is now a "+typeof(myNumFixed));

Console Output:
"3.14 is now a string"


These are some basic built in parsers - used for transforming values.

Practice at:
http://jsbin.com



No comments:

Post a Comment