jiwonman
asked on
how do i convert decimal to fraction in Java?
Thank you.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.in tValue())* Math.pow(10, numOfDecimals));
System.out.println(numerat or+"/"+ denomianator);
This is a test code that changes the deicmal to fraction. All you need to do is reduce the fraction further
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.in
System.out.println(numerat
This is a test code that changes the deicmal to fraction. All you need to do is reduce the fraction further
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.
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.
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 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.ma th.Fractio n class.
This method has the prototype:
static Fraction getFraction(double value)
This method has the prototype:
static Fraction getFraction(double value)
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?