# Decimal to Fraction method

• 07-16-2009, 01:53 AM
Chasingxsuns
Decimal to Fraction method
I'm trying to make a method to take a fraction and return it's decimal value.

Code:

```        public String toFraction(double a) {                 String result = "";                 int wholeNum = (int)a/1;                 double numerator = (a%1) * 10;                 int denominator = 10;                 while(numerator > denominator) {                         denominator = denominator * 10;                 }                 result = "(" + ((denominator * wholeNum) + numerator) + "/" + denominator + (")");                 return result;                         }```
This is what I have. It's works for simple decimals like 0.5 or any other tenths-place decimal. But if i input 0.125 it just gives me 1.25/10. Is there a way I either assign numerator to not be a decimal or to check it's value as a whole number? Also, I'm not worried about reducing fractions. I just want it to work right now before I make it reduce the fractions.
• 07-16-2009, 02:32 AM
Fubarable
Quote:

Originally Posted by Chasingxsuns
I'm trying to make a method to take a fraction and return it's decimal value.

I'm confused as your code appears to be trying to do the opposite: taking a decimal and translating it to a fraction. Given the inexact nature of floating point representation of decimal numbers, this would be a very difficult task to do, I think. You may need to clarify your question a bit. Best of luck.
• 07-16-2009, 02:42 AM
Chasingxsuns
oh...yeah I meant the opposite of what I said lol. Sorry about that. Decimal to fraction.