Java 四舍五入浮点数
我试图创建一个专门用于浮点精度管理的类 实际上,它需要您的双精度,小数位数必须四舍五入,然后每次您使用Java 四舍五入浮点数,java,double,floating-point-precision,Java,Double,Floating Point Precision,我试图创建一个专门用于浮点精度管理的类 实际上,它需要您的双精度,小数位数必须四舍五入,然后每次您使用set(double)修改它时,数字将自动四舍五入 public class Precision { public Precision(int rounding, double n) { setRounding(rounding); set(n); } public double get() { return th
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
您使用的公式似乎工作不正常。您可以尝试以下方法:
this.n = (int) (n * Math.pow(10, rounding)) / Math.pow(10, rounding);
什么是it“未按预期工作”的示例?返回一个
long
我在消息OK中添加了一个示例,所以此时您应该进行一些调试以隔离问题。噢,感谢我现在得到了它,我想改为执行Math.round(n*Math.pow(10,舍入))/Math.pow(10,舍入)
。@LoveMetal有一个错误,请参见编辑。将100.0更改为数学功率(10,四舍五入)
。