How to convert decimal to fractions?

前端 未结 10 2194
心在旅途
心在旅途 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:06

    You should find the greatest common divisor of the resulted numbers and divide the numerator and denominator by it.

    Here is one way to do it:

    public class Rational {
    
        private int num, denom;
    
        public Rational(double d) {
            String s = String.valueOf(d);
            int digitsDec = s.length() - 1 - s.indexOf('.');
            int denom = 1;
            for (int i = 0; i < digitsDec; i++) {
                d *= 10;    
                denom *= 10;
            }
    
            int num = (int) Math.round(d);
            int g = gcd(num, denom);
            this.num = num / g;
            this.denom = denom /g;
        }
    
        public Rational(int num, int denom) {
            this.num = num;
            this.denom = denom;
        }
    
        public String toString() {
            return String.valueOf(num) + "/" + String.valueOf(denom);
        }
    
        public static int gcd(int num, int denom) {
              ....
        }
    
        public static void main(String[] args) {
            System.out.println(new Rational(1.5));
        }
    }
    

提交回复
热议问题