Tải bản đầy đủ - 0 (trang)
Converting strings to numbers, numbers to strings

# Converting strings to numbers, numbers to strings

Tải bản đầy đủ - 0trang

Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/29.html

95

30

Controlling the length of decimals

The price of the item is \$9.95. The sales tax is 6.5% of the price. You combine the two

numbers to get the total.

var total = price + (price * taxRate);

The variable total now has a value of 10.59675.

But that isn't what you're going to charge the customer, is it? You're going to charge her an

amount rounded off to two decimal places: \$10.60.

Here's how to do it.

var prettyTotal = total.toFixed(2);

The statement above rounds the number represented by total to 2 places and assigns the

result to the variable prettyTotal. The number inside the parentheses tells JavaScript how

many places to round the decimal to.

Now add a dollar sign, and you're all set.

var currencyTotal = "\$" + prettyTotal;

To shorten a number to no decimals, leave the parentheses empty.

var prettyTotal = total.toFixed();

Unfortunately, the toFixed method comes with a surprise inside. If a decimal ends in 5, it

usually rounds up, as you would expect. But, depending on the browser, sometimes it rounds

down! If, for example, you apply the method to 1.555, specifying 2 decimal places, it may give

you "1.56". Or it may produce "1.55".

There are sophisticated ways to address the problem. Here's an inelegant fix that uses

methods you already know and understand.

1

2

3

4

5

6

var str = num.toString();

if (str.charAt(str.length - 1) === "5") {

str = str.slice(0, str.length - 1) + "6";

}

num = Number(str);

prettyNum = num.toFixed(2);

If the decimal ends in a 5, the code changes it to a 6 so the method is forced to round up

when it should. Here's what's happening, line-by-line:

96

1.

2.

3.

4.

5.

6.

Converts the number to a string and assigns it to the variable str.

Checks to see if the last character is "5".

If so, slices off the "5" and appends "6".

-Converts it back to a number.

Rounds it to 2 places.

97

Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/30.html

98

31

Getting the current date and time

Your webpage includes a notice telling the user the current local date and time in his

particular time zone. But what is the current date and time? Here's how JavaScript finds out.

var rightNow = new Date();

The statement above creates something called a Date object. This is what it looks like.

Note that JavaScript gets this information from the user's computer. It is only as accurate

as the computer's date and time settings. For example, if the user just moved from the U.S.

West Coast to the U.S. East Coast and hasn't reset the time zone on his computer, the computer

99

will still be on Pacific Time. The Date object, too, will be on Pacific Time.

The Date object may resemble a string, but it isn't one. For example, you can't use

methods on it like charAt, indexOf, or slice.

If you need the Date object to be a string, you can convert it to one the same way you

convert a number to a string.

var dateString = rightNow.toString();

The code above converts the Date object represented by the variable rightNow to a

string and assigns the string to the variable dateString.

Most of the time, you'll just want to extract some of the information from the Date object

without converting it to a string.

I'm going to show you how to extract the individual pieces of the Date object. In this

chapter I'll get you started with the first piece. In the next chapter I'll cover the rest.

The following code creates a new Date object, assigns it to the variable rightNow,

extracts the day of the week, and assigns the day of the week to the variable theDay.

1 var rightNow = new Date();

2 var theDay = rightNow.getDay();

In the diagram of the Date object that I showed you above, the day of the week was

represented as "Mon." But when you extract the day of the week from the object, it's

represented as a number. Days are designated by a number from 0 for Sunday through 6 for

Saturday. This means that you'll need a bit of code to convert it back into a day name like

"Mon."

1

2

3

4

var

var

var

var

dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

now = new Date();

theDay = now.getDay();

nameOfToday = dayNames[theDay];

Here's what's going on:

1.

2.

3.

4.

Creates an array of days starting with "Sun" and assigns it to dayNames.

Creates a new Date object and assigns it to now.

Extracts the day of the week as a number and assigns it to theDay.

Uses the day number as an index to specify the correct array element, i.e. the day name.

100

Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/31.html

101

32

Extracting parts of the date and time

Here's a summary of important methods for extracting pieces of the Date object.

I covered getDay in the last chapter. Let's look at the rest of the extraction methods. Like

getDay, getMonth gives you not the spelled-out name of the month shown in the Date object,

but a number. The following code produces a month number ranging from 0 for January through

11 for December.

1 var d = new Date();

2 var currentMonth = d.getMonth();

getDate

gives you a number for the day of the month.

var dayOfMonth = d.getDate();

getFullYear

gives you a 4-digit number for the year.

var currYr = d.getFullYear();

102

getHours

gives you a number from 0 through 23 corresponding to midnight through 11

p.m.

var currentHrs = d.getHours();

getMinutes

gives you a number from 0 through 59.

var currMins = d.getMinutes();

getSeconds

gives you a number from 0 through 59.

var currSecs = d.getSeconds()

getMilliseconds

gives you a number from 0 through 999.

103

var currMills = d.getMilliseconds();

getTime

gives you the number of milliseconds that have elapsed since midnight, Jan. 1,

1970.

var millsSince = d.getTime();

104

Find the interactive coding exercises for this chapter at:

http://www.ASmarterWayToLearn.com/js/32.html

105

### Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Converting strings to numbers, numbers to strings

Tải bản đầy đủ ngay(0 tr)

×