Concatenating a String and Another Data Type
By Stephen Bucaro
To concatinate two or more strings, use + (the concatination operator). To
concatinate a string and a number, also use the concatination operator. This is
because JavaScript coerces (converts) the number to a string. Shown below is an example:
var amt = 4.35;
var total = "The total is " + amt;
alert(total);
Result: The total is 43.45
Using the + operator with two numbers will add the two numbers and return
the sum. Shown below is an example:
var amt1 = 4.35;
var amt2 = 5.65;
var total = amt1 + amt2;
alert(total);
Result: 10
But using the + operator with a number in a string data type and a number
returns a string with an incorrect result. Shown below is an example:
var amt1 = 4.35;
var amt2 = "5.65";
var total = amt1 + amt2;
alert(total);
Result: 4.355.65
To use the + operator with a number, or numbers, in a string data type requires
passing the strings to either parseInt() or parseFloat() to convert
the strings to numbers. An example is shown below.
var strNum1 = "43";
var strNum2 = "35";
var total = parseInt(strNum1) + parseInt(strNum2);
alert(total);
Result: 78
More Java Script Code: • JavaScript to Generate a Random Number Between X and Y • Calculators For Your Web Site : Length Units Converter • Code to Add Music to Your Webpage • Easy Picture Panning Code • JavaScript Code for Binary to Hexadecimal - Hexadecimal to Binary Conversion • Date Picker For Your Web Site • Easy JavaScript Picture Selector Code • Code for Java Script Cube / Box Volume Calculator • How to Place Image on HTML5 Canvas • Use JavaScript parseInt() and parseFloat() to Convert Strings to Numbers
|