BigDecimal CompareTo 未按预期工作
根据 对于 BigDecimal
的 JavaDoc,compareTo
函数在比较过程中不考虑小数位数。
现在我有一个看起来像这样的测试用例:
BigDecimal result = callSomeService(foo);
assertTrue(result.compareTo(new BigDecimal(0.7)) == 0); //this does not work
assertTrue(result.equals(new BigDecimal(0.7).setScale(10, BigDecimal.ROUND_HALF_UP))); //this works
我期望函数返回的值是 0.7
并且比例为 10。打印该值会显示预期的结果。但是 compareTo()
函数似乎没有按照我认为应该的方式工作。
这是怎么回事?
According to the JavaDoc for BigDecimal
, the compareTo
function does not account for the scale during comparison.
Now I have a test case that looks something like this:
BigDecimal result = callSomeService(foo);
assertTrue(result.compareTo(new BigDecimal(0.7)) == 0); //this does not work
assertTrue(result.equals(new BigDecimal(0.7).setScale(10, BigDecimal.ROUND_HALF_UP))); //this works
The value I'm expecting the function to return is 0.7
and has a scale of 10. Printing the value shows me the expected result. But the compareTo()
function doesn't seem to be working the way I think it should.
What's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
new BigDecimal(0.7)
确实不代表 0.7。它代表 0.6999999999999999555910790149937383830547332763671875 (准确)。
其原因是
double
文字0.7
不能准确地表示 0.7。如果您需要精确
BigDecimal
值,则必须使用String
构造函数(实际上全部 不采用 double 值的构造函数也可以工作)。请尝试使用
new BigDecimal("0.7")
代替。的 JavaDoc BigDecimal(double)
构造函数 有一些相关注释:总结一下:如果您想创建一个具有固定十进制值的 BigDecimal,请使用 String 构造函数。如果您已经有一个
double
值,那么BigDecimal.valueOf(double)
将提供比使用新 BigDecimal(double)< /代码>
。
new BigDecimal(0.7)
does not represent 0.7.It represents 0.6999999999999999555910790149937383830547332763671875 (exactly).
The reason for this is that the
double
literal0.7
doesn't represent 0.7 exactly.If you need precise
BigDecimal
values, you must use theString
constructor (actually all constructors that don't takedouble
values will work).Try
new BigDecimal("0.7")
instead.The JavaDoc of the
BigDecimal(double)
constructor has some related notes:So to summarize: If you want to create a
BigDecimal
with a fixed decimal value, use theString
constructor. If you already have adouble
value, thenBigDecimal.valueOf(double)
will provide a more intuitive behaviour than usingnew BigDecimal(double)
.