Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Decimal to Fraction java

  • 24-03-2005 1:36pm
    #1
    Closed Accounts Posts: 133 ✭✭


    Is there a straight forward way of converting a decimal to a fraction in java.

    I can convert 4.25 to 425/100 alright, but ideally I'd like to display this as 17/4.

    I can multiply 4.25 by 100 then convert to an int and place it over 100.

    But I don't know where to begin when it comes to reducing 425/100 to 17/4.

    Any ideas of how to do this?

    Cheers


Comments

  • Registered Users, Registered Users 2 Posts: 4,003 ✭✭✭rsynnott




  • Closed Accounts Posts: 133 ✭✭Jim Kernsey


    That looks very complicated but i'll give it a shot


  • Closed Accounts Posts: 133 ✭✭Jim Kernsey


    got it

    public int hcf(int x, int y){
    int t = 0;
    while (y!= 0) {
    t = y;
    y = x % y;
    x = t;
    }
    return x;
    }

    if anyone wants to improve it, please do

    cheers JK


  • Registered Users, Registered Users 2 Posts: 1,184 ✭✭✭causal


    Java does it for you ;)

    causal


  • Registered Users, Registered Users 2 Posts: 1,184 ✭✭✭causal


    if anyone wants to improve it, please do
    1) Use sensible variable names (x, y, t is fine for cartesian coordinates and time)
    2) What happens your code when y > x

    Well you did ask... :)

    causal


  • Advertisement
  • Closed Accounts Posts: 133 ✭✭Jim Kernsey


    and i melted my head with Euclids's Algorithm :rolleyes: .....

    Thanks for that casual, I thought there had to be an easier way, couldn't find it when I googled, it pays to know what your looking for!


    Your point about y > x is noted , don't have to worry about that now :)

    Cheers

    JK


  • Registered Users, Registered Users 2 Posts: 1,184 ✭✭✭causal


    No problemo.

    In case you don't already know the java api javadoc is available online.

    And you can download it too (listed as J2SE 5.0 Documentation)

    It's the first place to look for anything in j2se :)
    btw - fair play to you for deriving your solution from Euclids algorithm :cool:

    hth,
    Al


Advertisement