将所有BigDecimal操作设置为一定的精度? [英] Set all BigDecimal operations to a certain precision?
问题描述
我的Java程序集中在高精度计算上,该计算必须精确到至少120个小数位.
因此,程序中所有非整数都将由BigDecimals表示.
My Java program is centered around high precision calculations, which need to be accurate to at least 120 decimal places.
Consequentially, all non-integer numbers will be represented by BigDecimals in the program.
显然,我需要为BigDecimals指定舍入的精度,以避免无限的十进制表达式等.
目前,我发现在BigDecimal的每个实例化或数学运算中都必须指定准确性非常麻烦.
Obviously I need to specify the accuracy of the rounding for the BigDecimals, to avoid infinite decimal expressions etc.
Currently, I find it a massive nuisance to have to specify the accuracy at every instantiation or mathematical operation of a BigDecimal.
是否可以为所有BigDecimal计算设置全局精度"?
(例如python中的 Decimal 模块的 Context.prec()
)
Is there a way to set a 'global accuracy' for all BigDecimal calculations?
(Such as the Context.prec()
for the Decimal module in python)
谢谢
规格:
Java jre7 SE
Windows 7(32)
Specs:
Java jre7 SE
Windows 7 (32)
推荐答案
(几乎)原始
不是那么简单,但是您可以创建 MathContext
并将其传递给所有 BigDecimal
构造函数和执行操作的方法.
Not as simple, but you can create a MathContext
and pass it to all your BigDecimal
constructors and the methods performing operations.
修订版
或者,您可以扩展 BigDecimal
并通过提供正确的 MathContext
并使用 divide
:
Alternatively, you can extend BigDecimal
and override any operations you want to use by supplying the right MathContext
, and using the rounding version of divide
:
public class MyBigDecimal extends BigDecimal {
private static MathContext context = new MathContext(120, RoundingMode.HALF_UP);
public MyBigDecimal(String s) {
super(s, context);
}
public MyBigDecimal(BigDecimal bd) {
this(bd.toString()); // (Calls other constructor)
}
...
public MyBigDecimal divide( BigDecimal divisor ){
return new MyBigDecimal( super.divide( divisor, context ) );
}
public MyBigDecimal add( BigDecimal augend ){
return new MyBigDecimal( super.add( augend ) );
}
...
}
这篇关于将所有BigDecimal操作设置为一定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!