【发布时间】:2017-01-07 20:34:37
【问题描述】:
我应该使用MathContext.DECIMAL32 还是MathContext.DECIMAL64?我看过documentation,但我也不太明白什么时候使用。
我使用 BigDecimal 来表示我想应用于一定金额的百分比。像这样的:
...
final MathContext mc = MathContext.DECIMAL32;
BigDecimal amount = getAmount(args);
float percent = getPercent().floatValue();
BigDecimal percentAsBd = new BigDecimal(percent/100.f, mc).setScale(4, RoundingMode.HALF_UP);
BigDecimal threshold = amount.multiply(percentAsBd);
...
我正在使用 oracle java 1.8、ubuntu 14.04、Intel core i7 (64bit)
【问题讨论】:
-
任何你觉得你应该使用其中一个的特殊原因,而不是构造一个符合你要求的 MathContext,例如四舍五入?
-
@PatriciaShanahan 我想我担心它与我认为是 32 位的 java 的本机浮点数的兼容性。
-
Java 的原生浮点数是基于二进制的,而不是十进制的,并且比 BigDecimal 更不适合表示百分比。我认为它的大小无关紧要。
-
@PatriciaShanahan;我认为
DECIMAL32和DECIMAL64上下文的精度分别或多或少与float和double匹配,并确保BigDecimal 不必使用BigInteger。 -
@has981:如果可以避免的话,不要将
float或double与BigDecimal混合使用。您应该使用BigDecimal来获得它提供的精度,而floats和doubles从未如此精确。而是直接用字符串初始化BigDecimals,或者longs。
标签: java floating-point bigdecimal mathcontext