将BRL货币值字符串解析为

时间:2018-03-27 16:19:43

标签: java string parsing format currency

我正在尝试解析以下字符串:“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)

2 个答案:

答案 0 :(得分:1)

您可以使用德语区域设置,因为它使用逗号作为小数分隔符,如上所述here in the documentation。像这样:

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

答案 1 :(得分:1)

此单元测试在 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 更改为 positivePrefix,其中 \00A0&nbsp; 而不是真正的空格字符。

见:Java Decimal Format parsing issue

相关问题