14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

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

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

Chapter 2 ■ Data <strong>and</strong> Decisions<br />

Let’s see how these functions work in practice:<br />

<br />

<br />

<br />

var userEnteredNumber = prompt( "Please enter a number", "" );<br />

document.write( typeof( userEnteredNumber ) );<br />

document.write( "" );<br />

document.write( parseFloat( userEnteredNumber ) );<br />

document.write( "" );<br />

document.write( parseInt( userEnteredNumber ) );<br />

userEnteredNumber = Number( userEnteredNumber )<br />

document.write( "" );<br />

document.write( userEnteredNumber );<br />

document.write( "" );<br />

document.write( typeof( userEnteredNumber ) );<br />

<br />

<br />

<br />

Try entering the value 23.50. You should get this output:<br />

string<br />

23.5<br />

23<br />

23.5<br />

number<br />

The data entered is read as a string in the first line. Then parseFloat() converts 23.50 from a string to a floating<br />

point number, <strong>and</strong> in the next line, parseInt() strips out the fractional part (<strong>with</strong>out rounding up or down). The<br />

variable is then converted to a number using the Number() function <strong>and</strong> stored in the userEnteredNumber variable itself<br />

(overwriting the string held there). On the final line, you see that userEnteredNumber’s data type is indeed number.<br />

Try entering 23.50abc at the user prompt:<br />

string<br />

23.5<br />

23<br />

NaN<br />

number<br />

The results are similar, but this time Number() has returned NaN. The parseFloat() <strong>and</strong> parseInt() functions still<br />

return a number because they work from left to right, converting as much of the string to a number as they can, <strong>and</strong><br />

then stop when they hit a nonnumeric value. The Number() function rejects any string that contains nonnumerical<br />

characters. (Digits, a valid decimal place, <strong>and</strong> + <strong>and</strong> – signs are allowed, but nothing else.)<br />

22<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!