|
Formatting and Parsing Numbers
Part:
1
2
(Continued from previous part...)
Output:
Default format: #,##0.### -> -1,234.568
Default number format: #,##0.### -> -1,234.568
Default currency format: ñ#,##0.00;(ñ#,##0.00) -> ($1,234.57)
Default percent format: #,##0% -> -123,457%
Pattern: #,##0.00 -> -1,234.57
Pattern: ñ#,##0.00 -> -$1,234.57
Pattern: ñ#,##0.00;(ñ#,##0.00) -> ($1,234.57)
Pattern: #,##0.00% -> -123,456.78%
Pattern (Japan): ñ#,##0.00 -> -?1,234.57
Note that:
- The factory methods getInstance() and getNumberInstance() return
DecimalFormat objects with the same formatting pattern.
- Rounding is used to remove the extra digits in the fraction part.
- If leading extra digits in the integer part will show up in the
output string. No no error, or truncation, will be given.
- The percent sign in pattern will convert the number by multiplying
with 100.
- The locale sensitive currency character will be replaced by the
specific currency sign of country setting in the default locale.
Parsing Strings for Numbers
DecimalFormat objects can also be used to parse strings for numbers.
Here is a demonstration program:
import java.util.*;
import java.text.*;
class NumberParsingTest {
public static void main(String[] a) {
parseNumbers();
}
public static void parseNumbers() {
DecimalFormat nf = new DecimalFormat("#,##0.00");
String ns = "-1234.5678";
Number nv = null;
DecimalFormat cf = new DecimalFormat("\u00A4#,##0.00");
String cs = "-$1234.5678";
Number cv = null;
DecimalFormat xf
= new DecimalFormat("\u00A4#,##0.00;(\u00A4#,##0.00)");
String xs = "($1234.5678)";
Number xv = null;
DecimalFormat pf = new DecimalFormat("#,##0.00%");
String ps = "-1234.5678%";
Number pv = null;
try {
nv = nf.parse(ns);
cv = cf.parse(cs);
xv = xf.parse(xs);
pv = pf.parse(ps);
} catch (ParseException e) {
System.out.println("Exception: " + e.toString());
}
System.out.println("Parsing " + ns + " with " + nf.toPattern());
System.out.println(" " + nv.doubleValue());
System.out.println("Parsing " + cs + " with " + cf.toPattern());
System.out.println(" " + cv.doubleValue());
System.out.println("Parsing " + xs + " with " + xf.toPattern());
System.out.println(" " + xv.doubleValue());
System.out.println("Parsing " + ps + " with " + pf.toPattern());
System.out.println(" " + pv.doubleValue());
}
}
Output:
Parsing -51,234.5678 with #,##0.00
-51234.5678
Parsing -$51234.5678 with ñ#,##0.00
-51234.5678
Parsing ($51234.5678) with ñ#,##0.00;(ñ#,##0.00)
-51234.5678
Parsing -51234.5678% with #,##0.00%
-512.345678
The result is very interesting:
- The grouping separator "," is not required in the input string.
- The number digits in the fraction part is not truly respected.
Part:
1
2
|