Java big decimal number format exception

后端 未结 3 2081
傲寒
傲寒 2021-02-19 11:03

Why does the code below throw a java number format exception?

BigDecimal d = new BigDecimal(\"10934,375\");
3条回答
  •  你的背包
    2021-02-19 11:41

    Yes, the BigDecimal class does not take any Locale into account in its constructor that takes a String, as can be read in the Javadoc of this constructor:

    the fraction consists of a decimal point followed by zero or more decimal digits.

    If you want to parse according to a different Locale, one that uses the comma as decimals separator, you need to use java.text.DecimalFormat with a specific Locale.

    Example:

    DecimalFormat fmt = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.GERMAN));
    fmt.setParseBigDecimal(true);
    BigDecimal n = (BigDecimal) fmt.parse("10934,375");
    

    Note: you need to get an instance of DecimalFormat (a subclass of NumberFormat) to be able to call the method setParseBigDecimal. Otherwise it returns a Double instead, which is a binary floating point number, and binary floating point numbers cannot accurately represent many decimal fractions. So that would cause a loss of accuracy in many cases.

提交回复
热议问题