3

我正在使用 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而不是上述错误。

感谢您

问候,

安库什

4

2 回答 2

10

每当将空值传递给我的应用程序崩溃

是的,它会的。这是记录在案的行为:

抛出: IllegalArgumentException - 如果numbernull或不是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);
于 2013-06-11T11:42:23.437 回答
2

扩展 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

不幸的是,我所知道的帮助程序库都没有提供这样的格式包装器,因此您必须将此类添加到您的项目中。

于 2015-05-05T15:02:36.213 回答