[英]Java big decimal number format exception
为什么下面的代码抛出了java数字格式异常?
BigDecimal d = new BigDecimal("10934,375");
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: 是的,
BigDecimal
类在其带有String
构造函数中不考虑任何Locale
,可以在此构造函数的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.DecimalFormat
with 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
. 注意 :您需要获取
DecimalFormat
( NumberFormat
的子类)的实例才能调用方法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 . 否则它返回一个
Double
,它是一个二进制浮点数,二进制浮点数不能准确地表示许多小数 。 So that would cause a loss of accuracy in many cases. 因此,在许多情况下会导致精度损失。
The problem is that constructor of BigDecimal
requires decimal number format where decimals come right after decimal dot .
问题是
BigDecimal
构造函数需要十进制数字格式,其中小数点在小数点后面.
instead of decimal comma ,
so the right format for this specific case would be: 而不是十进制逗号
,
所以这个特定情况的正确格式是:
BigDecimal d = new BigDecimal("10934.375");
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.