简体   繁体   English

Big Decimal vs double 提供更好的精度

[英]Big Decimal vs double which provides better precision

I found some code in legacy software and i was interested in knowing which provides better precision, as it currently is where it takes the double and calculates on them:我在遗留软件中找到了一些代码,我很想知道哪个提供了更好的精度,因为它目前是取双精度并计算它们的地方:

double doubleNum = (Math.round(55.88d * 100) - Math.round(2.33d * 100));

second option第二个选项

BigDecimal bnv = BigDecimal.valueOf(55.88);
BigDecimal bsv = BigDecimal.valueOf(2.33);

System.out.println(bnv.subtract(bsv).setScale(2));

Both produce the same output, my understanding was that using bigdecimal ensures that is more precise.两者都产生相同的 output,我的理解是使用 bigdecimal 确保更精确。 But there could be loss when converting double to BigDecimal但是将 double 转换为 BigDecimal 时可能会丢失

Also the first option there is possible loss when casting..也是第一个选项,在铸造时可能会丢失..

I always use BigDecimal, but in this case.我总是使用 BigDecimal,但在这种情况下。

Floating point like double is always just an ( imprecise ) approximation, a sum of powers of 2 - without any notion of precision = number of decimals.double这样的浮点数始终只是一个( 不精确的)近似值,即 2 的幂之和 - 没有任何精度概念 = 小数位数。 55.88 and 55.879999998 could be the exactly same value (same bytes). 55.88 和 55.879999998 可能是完全相同的值(相同的字节)。

BigDecimal solves that. BigDecimal解决了这个问题。 But you do not want a constructor with a double as argument, because then the precision is lost too.但是你不想要一个带有double作为参数的构造函数,因为那样精度也会丢失。 Use:利用:

BigDecimal bnv = new BigDecimal("55.88");
BigDecimal bsv = new BigDecimal("2.33");

Above both have a precision of 2, a multiplication will give a precision of 4.以上两者的精度均为 2,乘法的精度为 4。

With BigDecimal one sometimes must provide the resulting precision for rounding and such.使用 BigDecimal 有时必须提供舍入等结果的精度。

So BigDecimal is superior, where it not for its horrible cobolish expressions.所以 BigDecimal 是优越的,它不是因为它可怕的 cobolish 表达式。

BigDecimal is an exact way of representing numbers and is not impacted by rounding in the manner in which double does. BigDecimal是一种表示数字的精确方式,并且不会像double那样受到四舍五入的影响。 The issue of losing precision is when assigning to double, not when converting from double to BigDecimal.丢失精度的问题是在分配给 double 时,而不是在从 double 转换为 BigDecimal 时。

For more details, you can see this post: Double vs. BigDecimal?更多细节可以看这篇文章: Double vs. BigDecimal?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM