Number Formats
To print a formatted number in Java, perform these two steps:
Format the number as a string.
Print the string.
Simple, right? Of course, this is a little like the old recipe for rabbit stew:
Catch a rabbit.
Boil rabbit in pot with vegetables and spices.
Obviously, step 1 is the tricky part. Fortunately, formatting numbers
as strings is somewhat easier than catching a rabbit. The key class
that formats numbers as strings is
java.text.NumberFormat. This is an abstract
subclass of java.text.Format. Concrete subclasses
such as java.text.DecimalFormat implement
formatting policies for particular kinds of numbers.
public abstract class NumberFormat extends Format implements Cloneable
The static NumberFormat.getAvailableLocales()
method returns a list of all locales installed that provide number
formats. (There may be a few locales installed that only provide date
or text formats, not number formats.)
public static Locale[] getAvailableLocales()
You can request a NumberFormat object for the
default locale of the host computer or for one of the specified
locales in Table 16.1 using the static
NumberFormat.getInstance() method. For example:
NumberFormat myFormat = NumberFormat.getInstance();
NumberFormat canadaFormat = NumberFormat.getInstance(Locale.CANADA);
Locale turkey = new Locale("tr", "");
NumberFormat turkishFormat = NumberFormat.getInstance(turkey);
Locale swissItalian = new Locale("it", "CH");
NumberFormat swissItalianFormat = NumberFormat.getInstance(swissItalian);The ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access