23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

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

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

public class MinimumWage {<br />

public static void main(String[] args) {<br />

NumberFormat dollarFormat =<br />

NumberFormat.getCurrencyInstance(Locale.ENGLISH);<br />

double minimumWage = 5.15;<br />

System.out.println("The minimum wage is "<br />

+ dollarFormat.format(minimumWage));<br />

System.out.println("A worker earning minimum wage and working for<br />

forty");<br />

System.out.println("hours a week, 52 weeks a year, would earn "<br />

+ dollarFormat.format(40*52*minimumWage));<br />

}<br />

}<br />

This program prints:<br />

The minimum wage is $5.15<br />

A worker earning minimum wage and working for forty<br />

hours a week, 52 weeks a year, would earn $10,712.00<br />

<strong>Java</strong> I/O<br />

Notice how nicely the numbers are formatted. Nowhere did I add dollar signs, say that I<br />

wanted exactly two numbers after the decimal point, or say that I wanted to separate the<br />

thousands with commas. The NumberFormat class took care of that.<br />

There are limits to how far currency formatting goes. Currency formats may change the<br />

currency sign in different locales, but they won't convert the values (between U.S. and<br />

Canadian dollars or between U.S. dollars and British pounds, for example). Since conversion<br />

rates float from day to day and minute to minute, that's a bit much to ask of a static class. If<br />

you want to do this, you need to provide some source of the conversion rate information,<br />

either from user input or pulled off the network.<br />

16.3.5 Percent Formats<br />

Number formats can also handle percentages in a variety of international formats. In grammar<br />

school math you learned that a number followed by a percent sign is really one-hundredth of<br />

its apparent value. Thus, 50% is really decimal 0.5, 100% is 1.0, 10% is 0.1, and so on.<br />

Percent formats allow you to use the actual decimal values in your code but print out the<br />

hundred-times larger percent values in the output. You request the default locale's percentage<br />

formatter with the static method NumberFormat.getPercentInstance():<br />

public static final NumberFormat getPercentInstance()<br />

To get a percentage formatter for a different locale, pass the locale to<br />

NumberFormat.getPercentInstance():<br />

public static NumberFormat getPercentInstance(Locale inLocale)<br />

Example 16.5 prints a table of percents between 1% and 100%. Notice that doubles are used<br />

in the code, but integral percents appear in the output.<br />

406

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

Saved successfully!

Ooh no, something went wrong!