3

So, I was making a program, where I have the user insert a numerator and denominator, the program converts the pseudo-fraction, to a decimal. It works fine, just one thing. One, if I enter a fraction that is a repeating decimal, (ex. 1/3, 0.3333333...), I want either it say 0.33 repeat, or for irrational numbers, It would round it after let's say 7 digits, and then stop and have "... Irrational" after. How could I do this? Code is below.

package Conversions;

import java.util.*;

public class FractionToDecimal  {

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);
    }
}
}    
Dylan Black
  • 242
  • 3
  • 14

1 Answers1

2

You could use this:

DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.CEILING);

Add as many # as you want decimals and then ou can simply use it like this:

Double d = 12345.789123456;
System.out.println(df.format(d));

Using three # would give you for the example above: 12345.789 for instance.

Please note that you can pick your rounding mode of course.

Small other note: Next time you ask a question on SO, please show some research, there are thousands of post about this and thousands of tutorials online. It would be nice to show what you have tried, what doesn't work ...

LBes
  • 3,067
  • 1
  • 22
  • 52