NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers.
To use number format, first you have to get a locale instance.
Then you can set many attributes of the formatting. Like, you have the option to show comma, restrict the number of decimal places, and set minimum and maximum integer length. If you want to display ‘%’ with respect to locale then you have to use NumberFormat. Just don’t append ‘%’ as a string to your result. Do you want to show paranthesis like (3745) in place of “-” to denote a negative numer, then use NumberFormat. Like these, there are numerous uses.
You can check JavaDoc for more methods
This tells you how to do it..!!
NumberFormat numberFormat = NumberFormat.getInstance();
// setting number of decimal places
numberFormat.setMinimumFractionDigits(2);
numberFormat.setMaximumFractionDigits(2);
// you can also define the length of integer
// that is the count of digits before the decimal point
numberFormat.setMinimumIntegerDigits(1);
numberFormat.setMaximumIntegerDigits(10);
// if you want the number format to have commas
// to separate the decimals the set as true
numberFormat.setGroupingUsed(true);
// convert from integer to String
String formattedNr = numberFormat.format(12345678L);
// note that the output will have 00 in decimal place
// convert from decimal to String
numberFormat.format(12345.671D);
// format a String to number
Number n1 = null;
Number n2 = null;
n1 = numberFormat.parse("1,234");
n2 = numberFormat.parse("1.234");
// show percentage
numberFormat = NumberFormat.getPercentInstance();
numberFormat.format(0.98);
// answer will be 98%
This is how you use field positions with number format.
// Get a default NumberFormat instance.
NumberFormat numForm = NumberFormat.getInstance();
// Format some decimals using the pattern supplied above.
StringBuffer dest1 = new StringBuffer(24);
StringBuffer dest2 = new StringBuffer(24);
FieldPosition pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
dest1 = numForm.format(22.3423D, dest1, pos);
System.out.println("dest1 = " + dest1);
System.out.println("FRACTION is at: " + pos.getBeginIndex() +
", " + pos.getEndIndex());
dest2 = numForm.format(64000D, dest2, pos);
System.out.println("dest2 = " + dest2);
System.out.println("FRACTION is at: " + pos.getBeginIndex() +
", " + pos.getEndIndex());
/*
Output:
dest1 = 22.342
FRACTION is at: 3, 6
dest2 = 64,000
FRACTION is at: 6, 6
*/