Double vs. BigDecimal? [英] Double vs. BigDecimal?

查看:126
本文介绍了Double vs. BigDecimal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须计算一些浮点变量,我的同事建议我使用 BigDecimal 而不是 double ,因为它会更精确但是我想知道它是什么,以及如何最大限度地利用 BigDecimal

解决方案

BigDecimal是表示数字的确切方式。双人具有一定的精度。使用不同大小的双打(d1 = 1000.0和d2 = 0.001)可能会导致0.001的总和下降,因为幅度差异如此之大。使用BigDecimal,这不会发生。



BigDecimal的缺点是更慢,编程算法有点困难(由于+ - *和/没有超载)。



如果你正在处理金钱,或精度是必须的,请使用BigDecimal。否则双打往往足够好。



我建议您阅读 javadoc 的BigDecimal,因为它们比我在这里做的更好地解释了事情:)


I have to calculate some floating point variables and my colleague suggest me to use BigDecimal instead of double since it will be more precise. But I want to know what it is and how to make most out of BigDecimal?

解决方案

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.

The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way (due to + - * and / not being overloaded).

If you are dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles tend to be good enough.

I do recommend reading the javadoc of BigDecimal as they do explain things better than I do here :)

这篇关于Double vs. BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆