01: package gnu.text;
02:
03: import java.text.FieldPosition;
04:
05: public class RomanIntegerFormat extends java.text.NumberFormat {
06: private static RomanIntegerFormat newRoman;
07: private static RomanIntegerFormat oldRoman;
08:
09: public boolean oldStyle;
10:
11: public RomanIntegerFormat(boolean oldStyle) {
12: this .oldStyle = oldStyle;
13: }
14:
15: public RomanIntegerFormat() {
16: }
17:
18: public static RomanIntegerFormat getInstance(boolean oldStyle) {
19: if (oldStyle) {
20: if (oldRoman == null)
21: oldRoman = new RomanIntegerFormat(true);
22: return oldRoman;
23: } else {
24: if (newRoman == null)
25: newRoman = new RomanIntegerFormat(false);
26: return newRoman;
27: }
28: }
29:
30: static final String codes = "IVXLCDM";
31:
32: public static String format(int num, boolean oldStyle) {
33: if (num <= 0 || num >= 4999)
34: return Integer.toString(num);
35: StringBuffer sbuf = new StringBuffer(20);
36: int power = 3;
37: int unit = 1000;
38: for (; power >= 0; unit = unit / 10, power--) {
39: int digit = num / unit;
40: num -= digit * unit;
41: if (digit == 0)
42: continue;
43: if (!oldStyle && (digit == 4 || digit == 9)) {
44: sbuf.append(codes.charAt(2 * power));
45: sbuf.append(codes.charAt(2 * power + (digit + 1) / 5));
46: continue;
47: }
48: int rest = digit;
49: if (rest >= 5) {
50: sbuf.append(codes.charAt(2 * power + 1));
51: rest -= 5;
52: }
53: while (--rest >= 0) {
54: sbuf.append(codes.charAt(2 * power));
55: }
56: }
57: return sbuf.toString();
58: }
59:
60: public static String format(int num) {
61: return format(num, false);
62: }
63:
64: public StringBuffer format(long num, StringBuffer sbuf,
65: FieldPosition fpos) {
66: String str;
67: if (num > 0 && num < (oldStyle ? 4999 : 3999))
68: str = format((int) num, oldStyle);
69: else
70: str = Long.toString(num);
71: if (fpos != null) {
72: // Kludge because FieldPosition fields not settable (in JDK 1.1)!
73: long tval = 1;
74: int len = str.length();
75: for (int i = len; --i > 0;)
76: tval = 10 * tval + 9;
77: // tval now has same number of digits as str
78: StringBuffer tbuf = new StringBuffer(len);
79: new java.text.DecimalFormat("0").format(tval, tbuf, fpos);
80: }
81: sbuf.append(str);
82: return sbuf;
83: }
84:
85: public StringBuffer format(double num, StringBuffer sbuf,
86: FieldPosition fpos) {
87: long inum = (long) num;
88: if ((double) inum == num)
89: return format(inum, sbuf, fpos);
90: sbuf.append(Double.toString(num));
91: return sbuf;
92: }
93:
94: public java.lang.Number parse(String text,
95: java.text.ParsePosition status) {
96: throw new Error(
97: "RomanIntegerFormat.parseObject - not implemented");
98: }
99: }
|