Java Reference
In-Depth Information
Display 2.3
Currency Format (part 2 of 2)
Sample Dialogue
Without formatting:
19.8
19.81111
19.89999
19
Default location:
$19.80
$19.81
$19.90
$19.00
This assumes that the system is set to
use U.S. as the default location. If you are
not in the U.S., you will probably get the
format for your local currency.
US as location:
$19.80
$19.81
$19.90
$19.00
This should give you the format for U.S.
currency no matter what country has been
set as the default location.
returns the String value "$19.80" , assuming the default currency is the U.S. dollar. In
Display 2.3, this method invocation occurs inside a System.out.println statement,
but it is legal anyplace a String value is legal. For example, the following would be
legal:
String moneyString = moneyFormatter.format(19.8);
In order to make the class NumberFormat available to your code, you must include
the following near the start of the file with your program:
import java.text.NumberFormat;
This is illustrated in Display 2.3.
The method invocation NumberFormat.getCurrencyInstance() produces an object
that formats numbers according to the default location. In Display 2.3, we are assum-
ing the default location is the United States, and so the numbers are output as U.S.
dollars. On other systems, the default should be set to the local currency. If you wish,
you can specify the location, and hence the local currency, by giving an argument to
NumberFormat.getCurrencyInstance . For example, in Display 2.3 we used the con-
stant Locale.US to specify that the location is the United States. The relevant line from
Display 2.3 is repeated in what follows:
NumberFormat moneyFormatter2 =
NumberFormat.getCurrencyInstance(Locale.US);
 
Search WWH ::




Custom Search