扩展 DecimalFormat 会破坏其 API(Jon Skeet 正确指出),但您可以实现自己的 Format 来包装给定的 DecimalFormat:
public class OptionalValueFormat extends Format {
private Format wrappedFormat;
private String nullValue;
public OptionalValueFormat(Format wrappedFormat, String nullValue) {
this.wrappedFormat = wrappedFormat;
this.nullValue = nullValue;
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
if (obj == null) {
// Just add our representation of the null value
return toAppendTo.append(nullValue);
}
// Let the default format do its job
return wrappedFormat.format(obj, toAppendTo, pos);
}
@Override
public Object parseObject(String source, ParsePosition pos) {
if (source == null || nullValue.equals(source)) {
// Unwrap null
return null;
}
// Let the default parser do its job
return wrappedFormat.parseObject(source, pos);
}
}
这不会破坏 的 API java.text.Format
,因为它只需要toAppendTo
并且pos
不为空。
的用法示例OptionalValueFormat
:
DecimalFormat df = ...
OptionalValueFormat format = new OptionalValueFormat(df, "0.00");
System.out.println(format.format(new java.math.BigDecimal(100)));
System.out.println(format.format(null));
结果:
100
0.00
不幸的是,我所知道的帮助程序库都没有提供这样的格式包装器,因此您必须将此类添加到您的项目中。