Java big decimal number format exception

╄→尐↘猪︶ㄣ 提交于 2019-12-22 03:48:14

问题


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

BigDecimal d = new BigDecimal("10934,375");

回答1:


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.




回答2:


The problem is that constructor of BigDecimal requires decimal number format where decimals come right after decimal dot . instead of decimal comma , so the right format for this specific case would be:

BigDecimal d = new BigDecimal("10934.375");



回答3:


You can use NumberFormat to choose the Locale, see the example:

        String numberToFormat = "1.900,35";
        NumberFormat formatter = NumberFormat.getNumberInstance(Locale.GERMAN);
        Number number = formatter.parse(numberToFormat);
        BigDecimal decimal = BigDecimal.valueOf(number.doubleValue());


来源:https://stackoverflow.com/questions/22454133/java-big-decimal-number-format-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!