# Thread: Decimal to Fraction method

1. Member
Join Date
Jul 2009
Posts
56
Rep Power
0

## Decimal to Fraction method

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

Java 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.

2. 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.

3. Member
Join Date
Jul 2009
Posts
56
Rep Power
0
oh...yeah I meant the opposite of what I said lol. Sorry about that. Decimal to fraction.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•