Pages

Thursday, December 22, 2011

Make sure 33 + 33 = 66 in your JavaScript code

As useful as JavaScript is, it doesn't always convert values into their appropriate data types when you perform an operation on them. For instance, in many scripting languages, the statement "33" + 33 would produce 66, despite the fact that the first value is a string, instead of a number.

In JavaScript, however, the above expression produces:

3333

As a result, you must convert values manually. This is because the + character, in addition to being the addition symbol, is also the concatenation character.

String to number conversions play an especially important role when you retrieve values from JavaScript cookies. JavaScript stores all cookie values as one big string. As a result, if the cookie contains a number, and then you want to perform some basic mathematical operation on it later, you'll need to convert it to the proper data type--in this case, a number.

Fortunately, JavaScript provides two main functions to do so: parseInt() and parseFloat(). The parseInt() function converts a number into an integer (whole numbers only), while parseFloat() converts value into a floating-point value. The following HTML page shows an example of how to use the two functions:

<html><head><title>Number conversion</title></head>
<body>
<script language="JavaScript" type="text/javascript">
var sNumInt = "33"
var sNumFlt = "33.23"

document.write("<h1>" + sNumInt + " + " + sNumFlt + " = "
+ (parseInt(sNumInt) + parseFloat(sNumFlt)) + "</h1>")
</script>

</body></html>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.