【问题标题】:How to convert currency formatted String back to a BigDecimal? (using Java NumberFormat)如何将货币格式的字符串转换回 BigDecimal? (使用 Java NumberFormat)
【发布时间】:2013-12-22 14:47:20
【问题描述】:

在我的 Android 应用程序中,我有一个 EditText,我从中获取一个数字,并将其转换为 BigDecimal,然后从那里转换为本地货币格式:

String s = "100000";
Locale dutch = new Locale("nl", "NL");
NumberFormat numberFormatDutch = NumberFormat.getCurrencyInstance(dutch);
Log.e(this, "Currency Format: "+ numberFormatDutch.format(new BigDecimal(s.toString())));

这会像预期的那样打印出 100.000,00 欧元。但是,我现在想将其转换回 BigDecimal。

有没有办法可以将本地格式化的货币字符串转换回 BigDecimal?

【问题讨论】:

  • 当你有 s 这是数字的基本表示时,你为什么要这样做?
  • 您可以使用正则表达式从字符串中去除所有非数字字符,例如str = str.replaceAll( "[^\\d]", "" ) 这并不能直接回答您的问题,因此这只是您可以采取的方法的建议。
  • @NigelK - 不幸的是,这没有考虑到在欧洲大陆(包括荷兰)我们使用逗号作为小数点,而大多数英语国家使用点作为小数点。由于这个原因,这已经失败了。
  • 你试过使用 numberFormatDutch.parse(myString, new ParsePosition(0));

标签: java android locale number-formatting


【解决方案1】:
    String s = "100000";
    Locale dutch = new Locale("nl", "NL");
    NumberFormat numberFormatDutch = NumberFormat.getCurrencyInstance(dutch);

    String c = numberFormatDutch.format(new BigDecimal(s.toString()));
    System.out.println("Currency Format: "+ c);
    try {
        Number  d = numberFormatDutch.parse(c);
        BigDecimal bd = new BigDecimal(d.toString());
        System.out.println(bd);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

货币格式:100.000,00 欧元

100000

【讨论】:

  • "有没有办法可以将本地格式化的货币字符串转换回 BigDecimal?" - 你的回答不会给他一个 BigDecimal 实例。
  • 该修复不适用于小数。将s 设置为“3.14”会将bd 设置为3.140000000000000124344978758017532527446746826171875。
  • 是的,你是对的,因为在 Java 上的双重实现,已编辑
【解决方案2】:

在您的代码示例中,您没有将 BigDecimal 分配给某些东西,因此您无法将其转换回来。

//Assign BigDecimal
BigDeciaml x = new BigDecimal(s.toString());
//Your code line
Log.e(this, "Currency Format: "+ numberFormatDutch.format(x));
//x it's the same as before
System.out.println(x);

希望对你有帮助!

【讨论】:

    【解决方案3】:

    我一直在努力寻找更好的解决方案,但这是迄今为止我遇到的最好的解决方案。它依赖于 NumberFromat.getCurrencyInstance 返回 DecimalFormat 的事实。我不喜欢强制转换它,但是 setParseBigDecimal 会导致 parse 方法返回 BigDecimal 而不是数字。还有另一个解析。我使用的是美国语言环境,但更改为 NL 很容易

    NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);
    DecimalFormat)fmt).setParseBigDecimal(true);
    BigDecimal amount = (BigDecimal)fmt.parse("$1,000,000.00");
    System.out.println(amount.toString());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多