Check if a double = 1/3

Viewed 1621

I have made a function that converts a double to a simplified fraction in Java:

public static int gcm(int a, int b) {
    return b == 0 ? a : gcm(b, a % b);
}
public static String toFraction(double d) {
    int decimals = String.valueOf(d).split("\\.")[1].length();
    int mult = (int) Math.pow(10, decimals);
    int numerator = (int) (d * mult);
    int denominator = mult;
    // now simplify
    int gcm = gcm(numerator, denominator);
    numerator /= gcm;
    denominator /= gcm;
    return numerator + "/" + denominator;
}

It works, except for the fact that if I use toFraction(1.0/3), this will, understandably, return "715827882/2147483647". How may I fix this to return "1/3"?

3 Answers
Related