Answer to Question #180242 in Java | JSP | JSF for tyresse gaffney

Question #180242

How do i convert a decimal into a fraction using a fraction reader and file with decimals


1
Expert's answer
2021-04-11T09:12:35-0400
public class Fraction {

        public static void fracion(double x) {
        String a = "" + x;
        String spilts[] = a.split("\\.");
        int b = spilts[1].length();
        int denominator = (int) Math.pow(10, b);
        int numerator = (int) (x * denominator);
                                                
        int gcd = getGCD(numerator, denominator);
                                                
        String fraction = "" + numerator / gcd + "/" + denominator / gcd;
        System.out.println(fraction);
    }

    public static int getGCD(int n1, int n2) {
        if (n2 == 0) {
            return n1;
        }
        return getGCD(n2, n1 % n2);
    }

    public static void main(String[] args) {

        fracion(0.35);
        fracion(1.2);
    }

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog