Java Reference
In-Depth Information
object. For example, if you intend to use it for formatting percentages,
you might code:
NumberFormat fmt = NumberFormat.getPercentInstance();
SR 3.26
a. The statement is:
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
Do not forget, you also must import
java.text.NumberFormat
into
your program.
b. The statement is:
System.out.println(moneyFormat.format(cost));
c. If the locale is the United States, the output will be
$54.89
. If the
locale is the United Kingdom, the output will be
£54.89
.
SR 3.27
To output a floating point value as a percentage, you first obtain a
NumberFormat
object using a call to the static method
getPercentage-
Instance
of the
NumberFormat
class. Then, you pass the value to be
formatted to the
format
method of the formatter object, which returns
a properly formatted string. For example:
NumberFormat fmt = NumberFormat.getPercentageInstance();
System.out.println (fmt.format(value));
SR 3.28
The following code will prompt for and read in a
double
value from the
user and then print the result of taking the square root of the absolute
value of the input value to two decimal places:
Scanner scan =
new
Scanner (System.in);
DecimalFormat fmt =
new
DecimalFormat("0.00");
double
value, result;
System.out.print ("Enter a double value: ");
value = scan.nextDouble();
result = Math.sqrt(Math.abs(value));
System.out.println (fmt.format(result));
3.7
Enumerated Types
SR 3.29
The following is a declaration of an enumerated type for movie ratings:
enum
Ratings {G, PG, PG13, R, NC17}
SR 3.30
Under the listed assumptions, the output is:
clubs
hearts
0
2
Search WWH ::
Custom Search