Type Conversion in JS

Javascript has loosely typed language or dynamic type language. It automatically converts the data into the right type, but it creates problems when we work on calculation-related applications. When we use the + operator it gives the wrong output it does not add values of input instead of it concatenates the values of input and gives the wrong output.

Javascript provides a number of ways to convert data from one type to another type but there is two most common type conversion:

  • Numeric Conversion
  • String Conversion

 

Numeric Conversion: It is used to convert data into a number format. There are two methods available in js to convert data into numbers which are the following:

  • parseInt(): It is used to convert data into integer format. It does not contain decimal numbers.
 
Example: 
 
var a=”5”;
 
var b=parseInt(a);
 

b will return numeric 5.

 

  • parseFloat): It is used to convert data into decimal format.
Example:
var a=’5.5’;
b=parseFloat(a);

b will give decimal format.

 

Example:  Find the largest of three number

<!DOCTYPE html>
<html>
<head>
</head>
 
<body>
 
<input type="text" id="num1">
<input type="text" id="num2">
<input type="text" id="num3">
 
<button type="button" onclick="check()">check</button>
 
<script>
function check()
{
   var num1 = parseInt(document.getElementById("num1").value);
   var num2 = parseInt(document.getElementById("num2").value);
    var num3 = parseInt(document.getElementById("num3").value);
  
   if(num1>num2 && num1>num3)
   {
     alert("num1 is greatest");
   }
  
   else if(num2>num1 && num2>num3)
   {
     alert("num2 is greatest");
   }
  
   else if(num3>num1 && num3>num2)
   {
     alert("num3 is greatest");
   }
  
   else
   {
     alert("invalid input");
   }
  
  
}
</script>
 
</body>
</html>
 

Here in this example, we have used the parseInt() method to convert input value into integer format.

Note: text input always gives value in string format so you should keep in mind to convert input value in integer format if you want to perform calculation, condition,s, etc.

 

String Conversion: It is used to convert data into string format. There are two functions available in JS which are following:

  • String()
  • toString()
 
Example: String() Function
Syntax:  String(value);
var a=5;
var b=String(a);

b will return “5” in string format.

 

Example:  toString() function
Syntax: variablename.toString();
var a=”5”;
var b=a.toString();

b will return “5” in string format.

Categories: web designing javascript front end developer

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 20 Days

Crash : 7 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 7 Month

Fastrack : 4 Month

Crash : 2 Month

Related Blogs

Request For Demo