Double vs. BigDecimal?

前端 未结 6 2196
梦谈多话
梦谈多话 2020-11-22 02:19

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. Bu

6条回答
  •  孤街浪徒
    2020-11-22 02:41

    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 :)

提交回复
热议问题