This is the changing from a data-type to another. For example, integer to float, float to string, string to integer and so forth. This is also known as CASTING. The following in-built JS functions are used for conversion.
parseInt()
parseFloat()
String()
Number()
and a .toString() method.
Consider the following statements,
var count1 = "5";
var count2 = 6;
count1 + count2 //would result in 56.
This is so because both variables are of different data-types. count1 is of string type and count2 is of integer type. These two data-types cannot be have an arithmetic computation between them. JavaScript will result to concatenate these two values.
To have a proper calculation performed between both variables, the variable with string type must be cast into integer type.
parseInt() / Number() function can be used here to convert string to integer. It is used thus,
Number(count1) + count2 //This will result in an 11
parseInt(count1) + count2 //This will result in an 11.
String() function is used to convert values to string type. For example,
var num1 = 4;
var num2 = String(num1);
Num2 variable also has the value of 4 only that it is stringed. An alert(num2); will output "4" (Four with the quotes)
parseFloat()
This JS function is used to convert a numeric stringed value to a floating point number. Floating point numbers are numbers with decimal places e.g 34.003.
var value1 = "3423.34";
var value2 = parseFloat(value1); //This passes a true floating point value 3423.34 to value2 variable.
parseFloat("23.00"); //This outputs integer value 23.
parseFloat("23.01");//This outputs floatnumber 23.01.
parseFloat("How"); // Outputs NaN which means not a number. How is not a number.
Comments are welcome to the comment section of this blog.
Joseph Kayode Agbede
MCITP, RHCE and ITIL certified
This comment has been removed by the author.
ReplyDelete