How to convert decimal to fractions?

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

    I tried adding this as an edit, but it was denied. This answer builds off of @Hristo93's answer but finishes the gcd method:

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

提交回复
热议问题