Java大十进制数格式异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22454133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:48:26  来源:igfitidea点击:

Java big decimal number format exception

javaexceptionbigdecimal

提问by The amateur programmer

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

为什么下面的代码会抛出java数字格式异常?

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

采纳答案by The amateur programmer

The problem is that constructor of BigDecimalrequires 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需要十进制数字格式,其中小数在十进制点之后.而不是十进制逗号,,因此这种特定情况的正确格式是:

BigDecimal d = new BigDecimal("10934.375");

回答by Erwin Bolwidt

Yes, the BigDecimalclass does not take any Localeinto account in its constructor that takes a String, as can be read in the Javadoc of this constructor:

是的,BigDecimal该类Locale在其构造函数中没有考虑任何采用 a 的构造函数,String可以在此构造函数的 Javadoc 中读取:

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.DecimalFormatwith a specific Locale.

如果你想根据不同的解析Locale,一个使用逗号作为小数分隔符,你需要使用java.text.DecimalFormat一个特定的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 Doubleinstead, 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.

注意:您需要获得DecimalFormat(的子类NumberFormat)的实例才能调用该方法setParseBigDecimal。否则返回一个Double替代,它是一个二进制浮点数,而二进制浮点数不能准确表示许多十进制小数。所以在很多情况下这会导致准确性的损失。

回答by Raul Guiu

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

您可以使用 NumberFormat 来选择 Locale,请参见示例:

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