Free programming examples and instructions

Convert to integer

How to convert to integer in javascript

by Athil

Posted on 14 Jun 2017 Category: Javascript Views: 718

Edited on 14 Jun 2017

Hi, here I am going to show how to convert to an integer in Javascript, I javascript user can't define a variable as a datatype. The computer understands the data types as for how the value stored in it. In such cases, we need to take care more in concatenating of variables and adding values in the variables.


To convert tot int in javascript use parseInt() method

For Example

 var a = 10;

var b = 20 ;

alert(a+b); // Results 30

In the above code results 30, because all the variables contains value integer.

var a = 'hi';

var b = 20;

alert(a+b); // results hi20

In the above code, The results become hi30 Because one of the variable contains string and another contains integer.

var a = 10;

var b = 20;

var c= 'hi';

alert( a+b+c); // results 30hi

Because the first two variables are integer and the last value is a string;

var a = 10;

var b = '20';

var c = 'hi';

alert(c+a+b); // results hi1020

Because the first calculations is a  string with a number and take the results as a string then computer do the last calculation with the string also be a string.


 So If you want to calculate a integer in between an operations with string use parseInt().

let's see how to use

var a = 10;

var b=20;

var c = 'hi'

alert(c+parseInt(a+b)); // Results hi30

Leave a Comment: