How to convert decimal to fractions?

前端 未结 10 2188
心在旅途
心在旅途 2020-12-06 06:26

What I need to convert decimal to fractions. It is easy to convert to 10\'s feet.

1.5 => 15/10

This can do via this code:



        
10条回答
  •  遥遥无期
    2020-12-06 07:05

    static private String convertDecimalToFraction(double x){
        if (x < 0){
            return "-" + convertDecimalToFraction(-x);
        }
        double tolerance = 1.0E-6;
        double h1=1; double h2=0;
        double k1=0; double k2=1;
        double b = x;
        do {
            double a = Math.floor(b);
            double aux = h1; h1 = a*h1+h2; h2 = aux;
            aux = k1; k1 = a*k1+k2; k2 = aux;
            b = 1/(b-a);
        } while (Math.abs(x-h1/k1) > x*tolerance);
    
        return h1+"/"+k1;
    }
    

    I got this answer from here. All I had to do is convert his answer to java.

提交回复
热议问题