我已經完成了我的g通過使用我自己的格式化程序使用標準格式化程序並使用exeptions查找禁止的符號。希望它對別人有用。
public static String getFormattedNumberWithPattern(String aPattern,
float aNumber) {
String lFormattedNumber = null;
String lOriginalPattern = aPattern;
try {
Hashtable<Integer, String> lIlligalChars = new Hashtable<Integer, String>();
// analyze illegal characters
for (int i = aPattern.length() - 1; i >= 0; i--) {
char[] lAux = new char[1];
aPattern.getChars(i, i + 1, lAux, 0);
try {
// if character is illegal, it throws an exception
@SuppressWarnings("unused")
NumberFormat lNumberFormatter = new DecimalFormat("#"
+ lAux[0] + "#");
} catch (IllegalArgumentException e) {
// add illegal chars and indexes to dictionary
lIlligalChars.put(new Integer(i), String.valueOf(lAux[0]));}}
Enumeration<String> lChars = lIlligalChars.elements();
while (lChars.hasMoreElements()) {
String lIllegalChar = lChars.nextElement();
// remove illegal chars from pattern
aPattern = removeChar(aPattern, lIllegalChar.charAt(0));
}
// format number using legal pattern
NumberFormat lNumberFormatter = new DecimalFormat(aPattern);
lFormattedNumber = lNumberFormatter.format(aNumber);
int lLenghtDifference = lOriginalPattern.length()
- lFormattedNumber.length();
// add illegal chars to formatted string using their indexes
Enumeration<Integer> lKeys = lIlligalChars.keys();
while (lKeys.hasMoreElements()) {
Integer lIllegalCharIndex = lKeys.nextElement();
int lInsertIndex = lIllegalCharIndex.intValue()
- lLenghtDifference;
// insert illegal chars into formatted number
if (lInsertIndex >= 0
|| lInsertIndex < lFormattedNumber.length()) {
lFormattedNumber = new StringBuffer(lFormattedNumber)
.insert(lInsertIndex,
lIlligalChars.get(lIllegalCharIndex)
.charAt(0)).toString();
}
}
} catch (Exception e) {
// Log.d("info", "formater error:" + e + "mask: " + aPattern
// + " number:" + aNumber);
}
return lFormattedNumber;
}
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c)
r.setCharAt(current++, cur);
}
r.setLength(current);
return r.toString();
}
來源
2011-10-11 14:49:01
fox