19.04.2017 Views

Learn to Program with Small Basic

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

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

Rounding <strong>to</strong> the Nearest Hundredth<br />

Let’s explore Listing 7-2 a bit more. Using Round() or Floor() on the answer<br />

gives you a whole number (dollars only). But what if you want <strong>to</strong> show the<br />

amount of money <strong>to</strong> the nearest penny? How can you make <strong>Small</strong> <strong>Basic</strong><br />

round the answer <strong>to</strong> the nearest hundredth? Consider this statement:<br />

Math.Floor(100 * x + 0.5) / 100<br />

For example, if x = 2.8735, then 100 * x + 0.5 = 287.85, and the Floor()<br />

method returns 287. Dividing 287 by 100 is 2.87, which is the result we want.<br />

You can also round <strong>to</strong> the nearest hundredth using this statement:<br />

Math.Round(x * 100) / 100<br />

Let’s use this second technique <strong>to</strong> round the answer from Listing 7-2 <strong>to</strong><br />

the nearest penny. Add the following statement after line 11 in Listing 7-2:<br />

A = Math.Round(A * 100) / 100<br />

After computing A in line 11, the program rounds it <strong>to</strong> the nearest hundredth<br />

(nearest penny) and saves the rounded answer back in A. If you run<br />

the program now using the original inputs, the output will be $3207.14.<br />

Perfect! Now we’re talking money!<br />

TRY IT OUT 7-2<br />

Helen is having a <strong>to</strong>ugh time at her s<strong>to</strong>re. She uses a calcula<strong>to</strong>r <strong>to</strong> add the 6% sales<br />

tax <strong>to</strong> the purchase price. For example, if a cus<strong>to</strong>mer’s <strong>to</strong>tal comes <strong>to</strong> $27.46, she<br />

multiplies 27.46 by 1.06 <strong>to</strong> get 29.1076. But should she charge the cus<strong>to</strong>mer $29.10<br />

or $29.11? She doesn’t have time <strong>to</strong> do these calculations herself! Her s<strong>to</strong>re keeps<br />

her much <strong>to</strong>o busy!<br />

Helen heard about your programming skills, so she’s coming <strong>to</strong> you for help.<br />

She needs a program that lets her enter the <strong>to</strong>tal purchase amount. Then she wants<br />

the program <strong>to</strong> add the sales tax, round the result <strong>to</strong> the nearest penny, and display<br />

the answer. Create this program for Helen.<br />

Abs(), Min(), and Max() Methods<br />

The Math object provides methods for you <strong>to</strong> find the absolute value of a<br />

number. When you calculate the absolute value of a number, you’re finding<br />

its distance from zero, which will always be a positive number. For example,<br />

the absolute value of both –1 and 1 is 1.<br />

88 Chapter 7

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

Saved successfully!

Ooh no, something went wrong!