我使用的是Java 1.6,我们使用java.text.DecimalFormat
格式化数字。例如
DecimalFormat df = new DecimalFormat();
df.setPositivePrefix("$");
df.setNegativePrefix("(".concat($));
df.setNegativeSuffix(")");
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
df.setGroupingSize(3);
df.format(new java.math.BigDecimal(100);
只要将null
值传递给df.format(null)
Error: cannot format given object as a number
我的问题是,我如何处理null
函数中的df.format()
值?
我想将null传递给df.format()
函数,并希望它返回0.00
而不是错误。
谢谢你
此致
Ankush
答案 0 :(得分:9)
每当将null值传递给
时,我的应用程序都会崩溃
是的,它会的。这是documented行为:
抛出:
IllegalArgumentException
-number
null
是Number
的实例。
下一步:
我想将null传递给df.format()函数,并希望它返回0.00而不是上面的错误。
不,那不行。据记载,它不起作用。只是不要通过null
...它很容易检测到。所以你可以用这个:
String text = value == null ? "0.00" : df.format(value);
或者
String text = df.format(value == null ? BigDecimal.ZERO : value);
答案 1 :(得分:2)
扩展DecimalFormat会破坏它的API(Jon Skeet正确指出),但你可以实现自己的包装给定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);
}
}
这不会破坏java.text.Format
的API,因为它只需要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
不幸的是,我所知道的帮助库都没有提供这样的格式包装器,所以你必须将这个类添加到你的项目中。