Main Page

Creating a conversion function

Creating a conversion function
A conversion function is relatively simple: You need two arguments, one for the value to be converted
and one indicating what type of conversion should take place. Generally speaking, three conversions are
frequently used: convert to integer, convert to float, and convert to date. Of course, if you need a string,
no conversion is necessary.
For this conversion function, the second argument is a string indicating the type of conversion to do:
?
“int” to convert to an integer
?
“float” to convert to a float
?
“date” to convert to a date
?
Any other value always returns a string
Here’s the function:
function convert(sValue, sDataType) {
switch(sDataType) {
case “int”:
return parseInt(sValue);
case “float”:
return parseFloat(sValue);
case “date”:
return new Date(Date.parse(sValue));
default:
return sValue.toString();
}
}
This function uses the
switch
statement to determine the value of
sDataType
(remember, the
switch
statement works on all types in JavaScript). When
sDataType
is
“int”
,
parseInt()
is called on
sValue
and the result is returned; when
sDataType
is
“float”
,
parseFloat()
is called and the result
is returned. If
sDataType
is
“date”
, then
Date.parse()
is used in conjunction with the
Date
construc-
tor to create and return a new
Date
object. If
sDataType
is any other value, the function returns
sValue.toString()
, to ensure that a string value is returned. This means that if
sDataType
is
“string”
,
null
, or any other value,
convert()
always returns a string. For example:
var sValue = “25”;
var iValue = convert(sValue, “int”);
alert(typeof iValue); //outputs “number”
var sValue2 = convert(sValue, “string”);
alert(typeof sValue2); //outputs “string”
var sValue3 = convert(sValue);
alert(typeof sValue3); //outputs “string”
var sValue4 = convert(sValue, “football”);
alert(typeof sValue4); //outputs “string”
In this example,
convert()
is used to convert the string
“25”
into an integer, meaning that when
typeof
is called against it, the value returned is
“number”
. If, however, the second argument is
378
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 378


JavaScript EditorFree JavaScript Editor     Ajax Editor


©