double a;

double b;

exp. a is greater or equals to b?

1.       a>b || Math.abs(a-b)<1e-6

2.       a.equals(b)

 

在实现中我需要小数点四位相等就判断相等,于是最后干脆直接包装double方便,这样差别很小的double型数是相等的(使用DecimalFormat转成String比较)

public class RValue implements Comparable<RValue>{
    private static DecimalFormat df = new DecimalFormat("0.0000");

    public static RValue min(RValue maxR, RValue rValue) {
        return maxR.compareTo(rValue)<0?maxR:rValue;
    }

    private String rValue;

    public RValue(double rValue){
        this.rValue = df.format(rValue);
    }
    public int compareTo(RValue o) {
        RValue rv = (RValue)o;
        double r1 = Double.valueOf(rValue);
        double r2 = Double.valueOf(rv.rValue);
        return r1>r2?1:(r1<r2?-1:0);
    }

    public int hashCode(){
        return rValue.hashCode();
    }

    public boolean equals(Object o){
        if(o instanceof RValue){
            RValue rv = (RValue)o;
            if(rv.rValue.equals(rValue))
                return true;
        }
        return false;
    }

    public String toString(){
        return rValue;
    }

}

 

这样效率肯定会比较低,但是使用方便。