Racket
Racket

Reputation: 327

Convert fraction to decimal number

i'm doing some exercises in my Java book. I'm very new to programming. Therefore, notice (in the code) that i'm still on Chapter one. Now I already did everything, I just want a confirmation if this is legitimate so I can feel free to move on next.

If not, I would sincerely appreciate to not do my code for me; I want advice.

Here's the question written in the book, "Write an application that prompts/reads the numerator and denominator of a fraction as integers, then prints the decimal equivalent of the fraction."

I'll illustrate this sentence with my code:

I did a revision here. Is this one OK?..

import java.util.*;
public class ExerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);

    double fraction;
    int fractionValue;
    int decimal;
    double value;

    System.out.println("Enter Numerator: ");
    int numerator = sc.nextInt();
    System.out.println("Enter Denominator: ");
    int denominator = sc.nextInt();

    fraction = (double) numerator / denominator;
    fractionValue = (int) (fraction * 10);
    decimal = fractionValue % 10;
    value = decimal * 0.1;


    System.out.println(value);
}
}

It compiles and works fine. Thank you.

Upvotes: 5

Views: 27384

Answers (4)

Saurav Sahu
Saurav Sahu

Reputation: 13924

There are three important parts of division operation :

  1. Sign of the result.
  2. Integral part
  3. Decimal part

Also, there are few corner cases where you need to deal with the fact that Integer.MIN_VALUE is greater than Integer.MAX_VALUE when compared in absolute form.

For example : -2147483648/-1 can't yield 2147483648 when divided in the form of integer types. The reason is simple. The type of the resulting type will be integer type, and the maximum positive value that a integer type variable can hold is +2147483647

To mitigate that scenario, we should at first convert both the numerator and denominator into their long positive form. That gives us the integral part of the answer.

The XOR of two numbers will have the sign bit as 1 only in case they have opposite signs. That solves the first part (sign of result) of the problem.

For decimal part, we can employ the general division rule i.e. multiply the remainder with 10 and try dividing again and repeat. Keep record of the remainder we have already come across to prevent the loop from going into unbounded iterations.

public String fractionToDecimal(int A, int B) {
    StringBuilder sb = new StringBuilder((A^B) < 0 ? "-" : "");
    long a = Math.abs((long)A);
    long b = Math.abs((long)B);
    sb.append(Long.toString(a/b));

    long rem = a % b; 
    sb.append((rem != 0) ? "." : "");
    Map<Long, Integer> remainderMap = new HashMap<>();
    int pos = 0;
    while (rem != 0){
        sb.append(Long.toString((rem*10)/b));
        remainderMap.put(rem, pos++);
        rem = (rem*10) % b;
        if (remainderMap.containsKey(rem)){
            String currNum[] = sb.toString().split("\\.");
            return currNum[0] + "." + currNum[1].substring(0, remainderMap.get(rem)) + 
                        "(" + currNum[1].substring(remainderMap.get(rem)) + ")";   
        }
    }
    if (sb.toString().equals("-0")) return "0"; 
    return sb.toString();
}

Sample output :

  • 2/3 gives 0.(6)

  • -2147483648/-1 gives 2147483648

Upvotes: 0

FalconBot
FalconBot

Reputation: 429

Hey I am doing some thinking about this and I have noticed something interesting after looking at this source and here is the Algorithm that I plan on implementing

  1. First I will convert the number from the Metric using the Javax.Measure family of functions and I will get a number like 0.3750
  2. Then I will divide the number by ONE_SIXTEENTH which = 0.0625
    ONE_SIXTEENTH = 0.0625
    The answer 0.3750 / ONE_SIXTEENTH = 6;
  3. So now I know there are 6 sixteenths of the inch
  4. Next I check to see if 6 is divisible by 4, 6/4 = 1.5 ie not a whole number so the fraction is still regarded as 6/16th of an inch for now
  5. Next I check to see if 6 is divisible by 2, 6/2 = 3 This is a whole number so we will use it to reconstitute the fraction
  6. So now that we have divided 6 by 2 and gotten 3 the 16 needs to be divided by 2 and we end up with 8 so 6/16th of an inch becomes 3/8th of an inch.

PS Has anyone noticed that this is similar to a fizz bang program?

____________________________________________

Here is the chart which helped me get my head around this

This is how I worked out how I was going to do this
My workings

Upvotes: 0

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43088

It doesn't do what task says it should. You read doubles instead of integers, and the decimal equivalent is not what you print out. Decimal equivalent for 1/2 is 0.5. And you print 5.

Also, you can pay attention to your code style: variable names are usually written in lowerCamelCase, like that : simpleVariable.

Update

now it prints what you need. However you do it not in the very right way and your indentation can still be improved.

Upvotes: 10

T.J. Crowder
T.J. Crowder

Reputation: 1074148

It's fine (I didn't read the assignment very well, did I? Kudos to Vladimir.) ...but some comments:

  • Usually you want to indent methods within the class.
  • Standard practice is to use initial caps (Numerator) only for types (e.g., classes, interfaces, enums). Variable, field, and method names should start with a lower-case letter. Now, you're free to ignore standard practice, but if you do people will have a lot of trouble reading your code. :-)
  • For rounding, you probably want to look at Math.round rather than truncating with a cast. But the assignment didn't say anything about rounding.
  • You might want to handle the case where denominator is zero.

So keeping those in mind:

import java.util.*;

public class ExcerciseEleven  {

    public static void main (String[] args) {
        Scanner sc = new Scanner (System.in);

        System.out.println("Enter Numerator: ");
        int numerator = sc.nextInt();
        System.out.println("Enter Denominator: ");
        int denominator = sc.nextInt();
        if (denominator == 0) {
            System.out.println("Can't divide by zero");
        }
        else {
            double fraction = (double)numerator / denominator;
            System.out.println(fraction);
        }
    }
}

Upvotes: 3

Related Questions