问题描述
我正在寻找一种精确的方法来在Java中将两个浮点数相乘,并且我读到我应该使用BigDecimal,但是它不能按预期工作.我在做什么错了?
I was searching for a precise way to multiply two floating point numbers in Java, and I read that I should use BigDecimal, however it doesn't work as expected. What am I doing wrong?
我的代码:
BigDecimal a = new BigDecimal(3.53);
BigDecimal b = new BigDecimal(3.59);
BigDecimal c = a.multiply(b);
System.out.println(c);
结果:
12.672699999999998796873512674210388041622697702955394242845497954075284496866515837609767913818359375
预期结果:
12.6727
推荐答案
使用 BigDecimal(double)
构造函数,它不能比double
更精确,请改用String
形式.喜欢,
When you use a BigDecimal(double)
constructor it cannot be more precise than a double
, use the String
form instead. Like,
BigDecimal a = new BigDecimal("3.53");
BigDecimal b = new BigDecimal("3.59");
BigDecimal c = a.multiply(b);
System.out.println(c);
哪个输出
12.6727
链接的Javadoc部分说明-
The linked Javadoc says in part -
-
此构造函数的结果可能有些不可预测.可能会假定使用Java编写新的
BigDecimal(0.1)
会创建一个BigDecimal
,该BigDecimal
完全等于0.1(未缩放的值1,小数位为1),但实际上等于0.1000000000000000055511151231257827021181583404541015625
.这是因为0.1不能精确地表示为double
(或者就此而言,可以表示为任何有限长度的二进制分数).因此,尽管出现,传递给构造函数的值并不完全等于0.1.
The results of this constructor can be somewhat unpredictable. One might assume that writing new
BigDecimal(0.1)
in Java creates aBigDecimal
which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to0.1000000000000000055511151231257827021181583404541015625
. This is because 0.1 cannot be represented exactly as adouble
(or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
String构造函数是完全可预测的:如人们所期望的那样,编写new BigDecimal("0.1")
会创建一个精确等于0.1的BigDecimal.因此,通常建议字符串构造函数优先于此函数使用.
The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1")
creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
这篇关于用Java精确地将两个数字相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!