DecimalFormat を拡張すると、その API が壊れます (Jon Skeet によって正しく指摘されました) が、指定された DecimalFormat をラップする独自の Format を実装できます。
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 を壊すことはありません。必要なのは null でないこと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
残念ながら、私が知っているヘルパー ライブラリの中で、このようなフォーマット ラッパーを提供しているものはないため、このクラスをプロジェクトに追加する必要があります。