Java Reference
In-Depth Information
Next, let's take a look at the formatDollars() method that is used in the code.
This method accepts a double value and performs formatting on it using the Num-
berFormat class based on the U.S. locale. It then returns a string value representing
currency:
public static String formatDollars(double value){
NumberFormat dollarFormat
= NumberFormat.getCurrencyInstance(Locale.US);
return dollarFormat.format(value);
}
As you can see, the NumberFormat class allows for currency to be formatted per
the specified locale. This can be very handy if you are working with an application that
deals with currency and has an international scope.
$217.83
$161.67
Note JSR 354, the Money and Currency API, was under development at the time of
this writing, and it is due to become part of Java 9. See the JSR for more information at
https://jcp.org/en/jsr/detail?id=354 .
How It Works
Many people attempt to use different number formats when working with currency.
While it might be possible to use any type of numeric object to work with currency, the
BigDecimal class was added to the language to help satisfy the requirements of
working with currency values, among other things. Perhaps the most useful feature of
the BigDecimal class is that it provides control over rounding. This is essentially
why such a class is so useful for working with currency values. The BigDecimal
class provides an easy API for rounding values, and also makes it easy to convert to
double values, as the solution to this recipe demonstrates.
Note The use of BigDecimal for working with monetary values is a good prac-
tice. However, it can come at some performance expense. Depending on the application
Search WWH ::




Custom Search