First of all, I would say that this class is very useful to print numbers on screen while managing the format they will have. Soon we will write another post about DecimalFormat, which inherits from this one.
NumberFormat is the simplest one. It mainly has these methods:
- getInstance() - Just obtains the current language format.
- getCurrencyInstance() - Same as getInstance, but with currency format.
and their overloads with a Locale parameter that will replace the current language.
To give the appropiate format it will be neccessary to invoke the format() method, as you will see next.
This class is a very adaptative util when formatting numbers. As always, I will look up the Java Docs to explain it, as it is our most appreciated resource ;-).
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class PruebaFormatos {
public static void main(String[] args) {
/*
* We start with getInstance() method, the simplest one.
* It just converts the numbers to the default locale format
* (Spanish in my case).
*/
NumberFormat nf = NumberFormat.getInstance();
System.out.println(nf.format(76543210.1234));
// Result: 76.543.210
// Now with a different locale (English)
nf = NumberFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format(76543210.1234));
// Result: 76,543,210
/*
* getIntegerInstance method, it rounds decimal numbers.
* Attention! it rounds, it doesn't truncate!
*/
nf = NumberFormat.getIntegerInstance();
System.out.println(nf.format(123456.789));
// Result: 123.457
// Now in French
nf = NumberFormat.getIntegerInstance(Locale.FRENCH);
System.out.println(nf.format(123456.789));
// Result: 123 457
/* I'll show you how to print the money I have in my bank account: */
nf = NumberFormat.getCurrencyInstance();
System.out.println(nf.format(12345678));
// Result: 12.345.678,00 € (That would be great! :-P)
// Now in US Dollars
nf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf.format(12345678 * 1.5023));
// Result: $18,546,912.06
/*
* At least, we are going to parse an integer. In this case it doesn't apply
* any format.
*/
try {
nf = NumberFormat.getInstance();
System.out.println(nf.parseObject("76543210 Euros"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}