【问题标题】:Parse BRL currency value String to double将 BRL 货币值字符串解析为加倍
【发布时间】:2018-09-06 03:48:03
【问题描述】:

我正在尝试解析以下字符串:“59000,00”

在巴西,逗号用于表示小数位,小数点用作分隔千位的符号。

我正在尝试做的事情:

final String price = "59000,00";
// LocaleUtils.getLocale returns new Locale("pt", "BR")
final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(LocaleUtils.getLocale());

try {
  final double d = numberFormat.parse(price).doubleValue();
  // do stuff
} catch (ParseException e) {
  // do stuff
}

但是,我收到了 ParseException。为什么会这样?

java.text.ParseException: Unparseable number: "59000,00" (at offset 8)

【问题讨论】:

  • 而你的代码没有返回预期的输出,抛出异常,还有别的吗?你没有问任何问题。
  • @luk2302 天哪!我遇到了一个例外,忘记在问题中提及这一点!已编辑。

标签: java string parsing format currency


【解决方案1】:

您可以使用德国语言环境,因为它使用逗号作为小数分隔符,如 here in the documentation 所述。像这样:

NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
double df = nf.parse(price).doubleValue();

【讨论】:

    【解决方案2】:

    此单元测试在 Java 8 中适用于我,但在 Java 11-15 中失败。

    @Test
    public void testBrazilianReal() throws ParseException {
         // Arrange
         Locale brazil = new Locale("pt", "BR");
         DecimalFormat format = (DecimalFormat) DecimalFormat.getCurrencyInstance(brazil);
         Double expected = Double.parseDouble("1234.56");
         ParsePosition pos = new ParsePosition(0);
    
         // Act
         Number result = format.parse("R$ 1.234,56", pos);
    
         // Assert
         assertEquals(expected, result, "Brazil locale");
    }
    

    Java 11 中,上述测试失败并...

    org.opentest4j.AssertionFailedError: Brazil locale ==> expected: <1234.56> but was: <null>
        at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
        
    

    更新:找到问题的根源。在 JDK11+ 中,他们将R$\00A0 更改为正前缀,其中\00A0&amp;nbsp;,而不是真正的空格字符。

    见:Java Decimal Format parsing issue

    【讨论】:

    • 我不得不从这两种空间中进行替换。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多