1 package net.sf.saxon.number; 2 import net.sf.saxon.om.FastStringBuffer; 3 4 import java.io.Serializable ; 5 import java.util.ArrayList ; 6 import java.util.List ; 7 8 13 14 public class NumberFormatter implements Serializable { 15 16 private ArrayList formatTokens; 17 private ArrayList punctuationTokens; 18 private boolean startsWithPunctuation; 19 20 32 33 public void prepare(String format) { 34 35 37 if (format.length()==0) format="1"; 38 39 formatTokens = new ArrayList (10); 40 punctuationTokens = new ArrayList (10); 41 42 int len = format.length(); 43 int i=0; 44 int t; 45 boolean first = true; 46 startsWithPunctuation = true; 47 48 while (i<len) { 49 char c = format.charAt(i); 50 t=i; 51 while (Character.isLetterOrDigit(c)) { 52 i++; 53 if (i==len) break; 54 c = format.charAt(i); 55 } 56 if (i>t) { 57 String tok = format.substring(t, i); 58 formatTokens.add(tok); 59 if (first) { 60 punctuationTokens.add("."); 61 startsWithPunctuation = false; 62 first = false; 63 } 64 } 65 if (i==len) break; 66 t=i; 67 c = format.charAt(i); 68 while (!Character.isLetterOrDigit(c)) { 69 first = false; 70 i++; 71 if (i==len) break; 72 c = format.charAt(i); 73 } 74 if (i>t) { 75 String sep = format.substring(t, i); 76 punctuationTokens.add(sep); 77 } 78 } 79 80 if (formatTokens.size() == 0) { 81 formatTokens.add("1"); 82 if (punctuationTokens.size() == 1) { 83 punctuationTokens.add(punctuationTokens.get(0)); 84 } 85 } 86 87 } 88 89 95 96 public CharSequence format(List numbers, int groupSize, String groupSeparator, 97 String letterValue, String ordinal, Numberer numberer) { 98 99 FastStringBuffer sb = new FastStringBuffer(20); 100 int num = 0; 101 int tok = 0; 102 if (startsWithPunctuation) { 104 sb.append((String )punctuationTokens.get(tok)); 105 } 106 while (num<numbers.size()) { 108 if (num>0) { 109 if (tok==0 && startsWithPunctuation) { 110 sb.append("."); 113 } else { 114 sb.append((String )punctuationTokens.get(tok)); 115 } 116 } 117 Object o = numbers.get(num++); 118 String s; 119 if (o instanceof Long ) { 120 long nr = ((Long )o).longValue(); 121 122 s = numberer.format(nr, (String )formatTokens.get(tok), 123 groupSize, groupSeparator, letterValue, ordinal); 124 } else { 125 s = o.toString(); 126 } 127 sb.append(s); 128 tok++; 129 if (tok==formatTokens.size()) tok--; 130 } 131 if (punctuationTokens.size()>formatTokens.size()) { 133 sb.append((String )punctuationTokens.get(punctuationTokens.size()-1)); 134 } 135 return sb.condense(); 136 } 137 138 } 139 140 | Popular Tags |