how do i convert decimal to fraction in Java?

Thank you.
Who is Participating?
objectsConnect With a Mentor Commented:
commons lang has a method for it

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.

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
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

jiwonmanAuthor Commented:
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)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.