Results 1 to 3 of 3
  1. #1
    psx2514 is offline Member
    Join Date
    Oct 2012
    Posts
    50
    Rep Power
    0

    Default Is there any way to get Java to output a number as a fraction rather than a decimal.

    For example if you asked it to display the result of (2/3) + (5/3), could you have it display the answer as 7/3 rather than 2.3333333333...?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Is there any way to get Java to output a number as a fraction rather than a decim

    There is nothing in the standard Java libraries to handle rational arithmetic. But there must be millions of examples of a Rational class a google away (it's a very common programming exercise), or you could write your own.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Is there any way to get Java to output a number as a fraction rather than a decim

    Even if you only have a double value 0.dddd ... (ignoring the integer part), it can be written as a fraction 10000 ... / dddd ... which can be simplified to (10000 .../gcd)/dddd .../gcd) where gcd is the greates common divisor of the numerator and denominator (there exist more advanced methods to find irreducable numerators and denominators).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. decimal to simplest form fraction
    By MonkeyMan in forum New To Java
    Replies: 1
    Last Post: 01-15-2012, 09:34 PM
  2. Output a Two Decimal Value
    By Hillsid3 in forum New To Java
    Replies: 7
    Last Post: 07-17-2011, 01:24 PM
  3. truncate a decimal number ?
    By hacikho in forum New To Java
    Replies: 5
    Last Post: 10-13-2010, 09:58 PM
  4. Converting whole number into decimal
    By jim01 in forum New To Java
    Replies: 2
    Last Post: 09-23-2010, 08:58 PM
  5. Decimal to Fraction method
    By Chasingxsuns in forum New To Java
    Replies: 2
    Last Post: 07-16-2009, 03:42 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
  •