【问题标题】:Number format always returns exception数字格式总是返回异常
【发布时间】:2014-06-03 10:00:36
【问题描述】:

我有以下代码

private boolean isRightMoneyValue(String value, String currencyIso) {
        Locale locale = new Locale(currencyIso);
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
        try {
            currencyFormatter.format(value);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

这个函数的输入是“1234567898.06789”作为值和“EUR”的currencyIso。 该方法总是导致异常。 不知道这里出了什么问题。

【问题讨论】:

  • 哪个例外?至少可以添加消息吗?
  • 您要求它格式化一个值...但该值已经是一个字符串。尝试传入 BigDecimal 代替...或使用 parse 代替 format
  • 不要在你的代码中吞下Exception,至少记录异常!

标签: java number-formatting


【解决方案1】:

Formatter#format 方法需要双精度值。所以,你应该传递双精度值而不是String

 private static boolean isRightMoneyValue(double value, String currencyIso) {
    Locale locale = new Locale(currencyIso);
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
    try {

        currencyFormatter.format(value);
    } catch (Exception e) {
        return false;
    }
    return true;
}

比这样称呼这个方法,

  boolean isValid = isRightMoneyValue(1234567898.06789,"EUR");

【讨论】:

  • 数字可以是 Number 的任何子类。
  • @anirudh,是的,这是另一种检查方式。
  • 当我使用您的代码时,我得到格式 ¤ 123,456.99 后的结果。我不知道这个 ¤ 符号是什么来的......
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多