04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3: Language Basics<br />

Most of the time you’ll be parsing decimal numbers, so it’s good to always include<br />

10 as the second argument.<br />

The parseFloat() function works in a similar way to parseInt() , looking at each character starting in<br />

position 0. It also continues to parse the string until it reaches either the end of the string or a character<br />

that is invalid in a floating - point number. This means that a decimal point is valid the first time it<br />

appears, but a second decimal point is invalid and the rest of the string is ignored, resulting in<br />

“22.34.5” being converted to 22.34.<br />

Another difference in parseFloat() is that initial zeros are always ignored. This function will recognize<br />

any of the floating - point formats discussed earlier, as well as the decimal and octal integer formats.<br />

Hexadecimal numbers always become 0. Because parseFloat() parses only decimal values, there is no<br />

radix mode. A final note: if the string represents a whole number (no decimal point or only a zero after<br />

the decimal point), parseFloat() returns an integer. Here are some examples:<br />

var num1 = parseFloat(“1234blue”); //1234 - integer<br />

var num2 = parseFloat(“0xA”); //0<br />

var num3 = parseFloat(“22.5”); //22.5<br />

var num4 = parseFloat(“22.34.5”); //22.34<br />

var num5 = parseFloat(“0908.5”); //908.5<br />

var num6 = parseFloat(“3.125e7”); //31250000<br />

The String Type<br />

The String data type represents a sequence of zero or more 16 - bit Unicode characters. Strings can be<br />

delineated by either double quotes ( “ ) or single quotes ( ‘ ), so both of the following are legal:<br />

var firstName = “Nicholas”;<br />

var lastName = ‘Zakas’;<br />

Unlike PHP, for which using double or single quotes changes how the string is interpreted, there is no<br />

difference in the two syntaxes in ECMAScript. A string using double quotes is exactly the same as a<br />

string using single quotes. Note, however, that a string beginning with a double quote must end with<br />

a double quote, and a string beginning with a single quote must end with a single quote. For example,<br />

the following will cause a syntax error:<br />

var firstName = ‘Nicholas”;<br />

//syntax error - quotes must match<br />

37

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!