我正在尝试创建一个专门用于浮点精度管理的类。
实际上,它需要你的双精度和小数位数,然后每次你都要用
set(double)
,数字将自动舍入。
public class Precision {
public Precision(int rounding, double n) {
setRounding(rounding);
set(n);
}
public double get() {
return this.n;
}
public void set(double n) {
this.n = Math.round(n * Math.pow(10, rounding)) / rounding;
}
public void inc(double n) {
set(get() + n);
}
public int getRounding() {
return this.rounding;
}
public void setRounding(int rounding) {
if (rounding > 324)
throw new UnsupportedOperationException("Can't round numbers after 324 decimals");
else
this.rounding = rounding;
}
public void copy(Precision p) {
this.rounding = p.getRounding();
this.n = p.n;
}
private int rounding;
private double n;
}
但它并没有像预期的那样工作,当我对数字进行运算时,它根本没有设置预期的数字。例如:
Precision p = new Precision(2, 0);
// Here p.n is worth 0.00
p.set(8.6596)
// Here p.n is worth 432.5
p.inc(3.2);
// Here p.n is worth 21785