I am trying to create a class dedicated to the floating point precision management.

Actually, it takes your double and the number of decimal it has to be rounded, then everytime you will modify it with set(double), the number will be automatically rounded.

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;
}

But it doesn't work as expected, when I do operations on the number it simply doesn't set the expected number. For instance:

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
有帮助吗?

解决方案

It seems like the formula you are using is not working properly. You can try this instead:

this.n = (int) (n * Math.pow(10, rounding)) / Math.pow(10, rounding);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top