Java Reference
In-Depth Information
itemCostAfterTax = itemCostAfterTax.toFixed(2);
document.write(“Item cost fixed to 2 decimal places is $“ + itemCostAfterTax);
The fi rst document.write() outputs the following to the page:
Item cost is $10.73925
However, this is not the format you want; instead you want two decimal places, so on the next line,
enter this:
itemCostAfterTax = itemCostAfterTax.toFixed(2);
You use the toFixed() method of the Number object to fi x the number variable that itemCostAfterTax
holds to two decimal places. The method's only parameter is the number of decimal places you want
your number fi xed to. This line means that the next document.write displays this:
Item cost fixed to 2 decimal places is $10.74
The fi rst thing you might wonder is why 10.74 and not 10.73 ? Well, the toFixed() method doesn't
just chop off the digits not required; it also rounds up or down. In this case, the number was 10.739 ,
which rounds up to 10.74 . If it'd been 10.732 , it would have been rounded down to 10.73 .
Note that you can only fi x a number from 0 to 20 decimal places.
Date Objects
The Date object handles everything to do with date and time in JavaScript. Using it, you can fi nd out the
current date and time, store your own dates and times, do calculations with these dates, and convert the
dates into strings.
The Date object has a lot of methods and can be a little tricky to use, which is why Chapter 10 is dedi-
cated to the date, time, and timers in JavaScript. You'll also see in Chapter 12 how you can use dates to
determine if there's been anything new added to the web site since the user last visited it. However, in
this section you'll focus on how to create a Date object and some of its more commonly used methods.
Creating a Date Object
You can declare and initialize a Date object in four ways. In the fi rst method, you simply declare a new
Date object without initializing its value. In this case, the date and time value will be set to the current
date and time on the PC on which the script is run.
var theDate1 = new Date();
Secondly, you can defi ne a Date object by passing the number of milliseconds since January 1, 1970, at
00:00:00 GMT. In the following example, the date is 31 January 2000 00:20:00 GMT (that is, 20 minutes
past midnight).
var theDate2 = new Date(949278000000);
Search WWH ::




Custom Search