创建自定义BigDecimal类型 [英] Creating a custom BigDecimal type
问题描述
在我的应用程序中,所有BigDecimal数字都按比例缩放以具有两位小数位.换句话说,每次我在代码中创建一个新的BigDecimal时,我也需要使用方法scale:
In my application, all BigDecimal numbers are scaled to have two decimal places.. In other words, everytime I create a new BigDecimal in my code, I need to use the method scale too:
BigDecimal x = BigDecimal.ZERO;
x.setScale(2, RoundingMode.HALF_UP);
因此,为了减少工作量,我想创建自己的自定义BigDecimal类型,例如:
So, to minimize the work, I wanted to create my custom BigDecimal type, something like:
public class CustomBigDecimal extends BigDecimal {
public CustomBigDecimal(String val) {
super(val);
this.setScale(2, RoundingMode.HALF_UP);
}
}
我知道this.setScale(2, RoundingMode.HALF_UP);
不能完成这项工作,但是我找不到解决方法,有可能吗?
I know this.setScale(2, RoundingMode.HALF_UP);
doesn't do the job, but I can't find the way to do it, is it possible?
推荐答案
您可以创建从BigDecimal
扩展的CustomBigDecimal
.但是,由于BigDecimal
是不可变的,因此您永远不会从父类继承状态(例如缩放和舍入模式).
You could create a CustomBigDecimal
that extends from BigDecimal
. However, as BigDecimal
is immutable, you would never inherit state (such as the scale and rounding mode) from the parent class.
我会去寻找另一个答案中建议的实用程序类,或者是将每个操作委派给实际BigDecimal
实例的包装器.这种方法的缺点是您全新的CustomBigDecimal
不会是BigDecimal
,因此它们将不能互换.
I'd go for the utility class suggested in another answer, or maybe a wrapper that delegates every operation to an actual BigDecimal
instance. The downside of this approach is that your brand new CustomBigDecimal
wouldn't be a BigDecimal
, so they wouldn't be interchangeable.
此方法的缺点是您必须委派大约50种方法.拥有出色的IDE并不是世界末日,但绝对不是很吸引人...
a downside of this approach is that you have to delegate about 50 methods. Not the end of the world with a good IDE, but definitely not very appealing...
如果毕竟您仍然想使CustomBigDecimal
从BigDecimal
继承,则需要使用 decorator 方法:
If, after all, you still want to make CustomBigDecimal
inherit from BigDecimal
, you'd need to use a decorator approach:
public class CustomBigDecimal extends BigDecimal {
private final BigDecimal value;
private CustomBigDecimal(BigDecimal value) {
super(value.toPlainString()); // needed to compile,
// useless except for implicit null-check
this.value = value;
}
public CustomBigDecimal(String val) {
this(new BigDecimal(val).setScale(2, RoundingMode.HALF_UP));
}
@Override
public CustomBigDecimal abs() {
return new CustomBigDecimal(this.value.abs());
}
// TODO all other methods
}
这篇关于创建自定义BigDecimal类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!