Results 1 to 3 of 3
  1. #1
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default 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. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by Chasingxsuns View Post
    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. #3
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    oh...yeah I meant the opposite of what I said lol. Sorry about that. Decimal to fraction.

Similar Threads

  1. Need help on Fraction
    By mitch25 in forum New To Java
    Replies: 2
    Last Post: 07-24-2009, 09:46 PM
  2. Replies: 3
    Last Post: 11-24-2008, 07:01 PM
  3. (Help) Fraction Summation and Exponents
    By SapphireSpark in forum New To Java
    Replies: 19
    Last Post: 10-09-2008, 04:01 AM
  4. Big Fraction 1.00
    By JavaBean in forum Java Software
    Replies: 1
    Last Post: 03-26-2008, 04:24 AM
  5. Trouble getting Julia fraction correct.
    By yllawwally in forum New To Java
    Replies: 0
    Last Post: 12-21-2007, 02:02 AM

Posting Permissions

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