import java.text.*; import java.util.*; /* * Format a number our way and the default way. */ public class NumFormat2 { /** A number to format */ public static final double data[] = { 0, 1, 22d/7, 100.2345678 }; /** The main (and only) method in this class. */ public static void main(String av[]) { // Get a format instance NumberFormat form = NumberFormat.getInstance( ); // Set it to look like 999.99[99] form.setMinimumIntegerDigits(3); form.setMinimumFractionDigits(2); form.setMaximumFractionDigits(4); // Now print using it. for (int i=0; i<data.length; i++) System.out.println(data[i] + "\tformats as " + form.format(data[i])); } }
This prints the contents of the array using the NumberFormat instance form:
$ java NumFormat2 0.0 formats as 000.00 1.0 formats as 001.00 3.142857142857143 formats as 003.1429 100.2345678 formats as 100.2346 $
You can also construct a DecimalFormat with a particular pattern or change the pattern dynamically using applyPattern( ). Some of the more common pattern characters are shown in the following.
# = Numeric digit (leading zeros suppressed)
0 = Numeric digit (leading zeros provided)
. = Locale-specific decimal separator (decimal point)
, = Locale-specific grouping separator (comma in English)
- = Locale-specific negative indicator (minus sign)
% = Shows the value as a percentage
; = Separates two formats: the first for positive and the second for negative values
, = Escapes one of the above characters so it appears
The NumFormatTest program uses one DecimalFormat to print a number with only two decimal places and a second to format the number according to the default locale:
// NumFormatTest.java /** A number to format */ public static final double intlNumber = 1024.25; /** Another number to format */ public static final double ourNumber = 100.2345678; NumberFormat defForm = NumberFormat.getInstance( ); NumberFormat ourForm = new DecimalFormat("##0.##"); // toPattern( ) shows the combination of #0., etc // that this particular local uses to format with System.out.println("defForm's pattern is " + ((DecimalFormat)defForm).toPattern( )); System.out.println(intlNumber + " formats as " + defForm.format(intlNumber)); System.out.println(ourNumber + " formats as " + ourForm.format(ourNumber)); System.out.println(ourNumber + " formats as " + defForm.format(ourNumber) + " using the default format");
This program prints the given pattern and then formats the same number using several formats:
defForm's pattern is #,##0.### 1024.25 formats as 1,024.25 100.2345678 formats as 100.23 100.2345678 formats as 100.235 using the default format
No comments:
Post a Comment