Link to home
Start Free TrialLog in
Avatar of jiwonman
jiwonman

asked on

how do i convert decimal to fraction in Java?

Thank you.
Avatar of a_b
a_b

Algorithm :-

Suppose you have 1.5, the decimal part if 0.5
-> Multiply the numerator and denominator by 10, you get 10/15.
-> Find the greated common divisor - 5.
-> Divide both numerator and denominator by 5, you get 2/3.

Thoughts?
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have no idea about the function in Commons Lang.
This is what I thought

        iint numerator = -1;
        int denomianator = -1;
        double d = 1.5;
        // Find num of decimal digits
        Double temp = new Double(d);
        String s = temp.toString(d);
        int numOfDecimals = s.length() - s.indexOf(".")-1;
        denomianator = (int) Math.pow(10, numOfDecimals);
        numerator = (int) (temp.intValue() * Math.pow(10, numOfDecimals) + (temp.floatValue()-temp.intValue())* Math.pow(10, numOfDecimals));
        System.out.println(numerator+"/"+ denomianator);
       

This is a test code that changes the deicmal to fraction. All you need to do is reduce the fraction further
Avatar of jiwonman

ASKER

a b .

do you think I can implement that to my previous problem? I wish I can try it but not enough time for me as of right now.

your method makes sense btw.
shouldn't the fraction be written as 1 and 1/2
here is what you need to do -

create a new function called void printFraction(double num)
move all convesion code within this function
when you do a sysout for the array, call this function Sysout(printFraction(array[i][j]));

I am sure you can do this, let  me know if you need any help.
You donot need to change the existing code/login, all you need to do is add code.
There is a method in org.apache.commons.lang.math.Fraction class.

This method has the prototype:

static Fraction getFraction(double value)