Let’s say I give you a decimal number say 3.5 and ask it to convert it into a fraction. You will quickly give me the answer as 7/2 and prompt “What’s the big deal in it”.
But if I ask you to convert it using a java program, then??? It won’t be too easy right.
Well, it is pretty much easy….Read on !!!
Java program to convert a decimal number into a fraction is given below.
import java.math.BigDecimal;
import java.util.Scanner;
public class Fraction {
//main method
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
//take user input
System.out.println("Enter the decimal number");
String input = scanner.nextLine();
int[] result = convertToFraction(input);
//output result
System.out.println(result[0] + "/" + result[1]);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (scanner != null) {
scanner.close();
}
}
}
/**
* Converts a number to fraction
* @param numberStr
* @return
* @throws Exception
*/
static int[] convertToFraction(String numberStr) throws Exception {
String[] parts = null;
try {
//parse the string to convert to a number
BigDecimal number = new BigDecimal(numberStr);
parts = number.toString().split("\\.");
//check if there was a decimal in the number
if (parts.length < 2) {
throw new ArrayIndexOutOfBoundsException("Error: Please ensure that"+
" the entered value has a decimal.");
}
} catch (NumberFormatException e) {
throw new Exception(
"Error: Please enter the number in proper format.");
} catch (ArrayIndexOutOfBoundsException ae){
throw ae;
}
/*
* Remove decimal
*/
// determine the denominator
BigDecimal den = BigDecimal.TEN.pow(parts[1].length());
// determine the numerator
BigDecimal num = (new BigDecimal(parts[0]).multiply(den))
.add(new BigDecimal(parts[1]));
return reduceFraction(num.intValue(), den.intValue());
}
/**
* Convert the numerator and denominator to their minimum values where no
* further cancellations are possible. For this we need to determine the
* common divisor of numerator and denominator elements
*
* @param num
* @param den
* @return
*/
static int[] reduceFraction(int num, int den) {
// get the gcd
int gcd = BigInteger.valueOf(num).gcd(BigInteger.valueOf(den))
.intValue();
// divide the numerator and denominator by gcd
int[] fractionElements = { num / gcd, den / gcd };
return fractionElements;
}
}
Output
Above program when executed gives the following result
Enter the decimal number.
10.9
109/10
10.9
109/10
- Read the fraction number as a string using Scanner class. Convert it to a
BigDecimal
. - Split it into two parts. One will be the numerator and other will be denominator. This is stored in an array.
- To remove the decimal, we need a multiplier of 10 with zeroes equal to the number of digits after the decimal. Keeping this is mind:
i. multiply 10 by the length of digits after decimal. This will be the lenngth of second element of the array in Step 2. This will give us the denominator of the fraction.
ii. Now the numerator can be determined by multiplying the part of the number before decimal (first element of array from Step 2) by the denominator determined in the previous step and adding the part of the number after decimal (second element of array from Step 2). - This gives us the numerator and denominator parts of our fraction. For example, if the number entered was 2.45, then our algorithm till this step will give us 245/100.
- Now we only need to reduce it to its lowest terms. For this we determine the greatest common divisor(gcd) of numerator and denominator and divide numerator and denominator (from Step 3) to get the fraction in lowest terms.
This code is written in reduceFraction method of the attached class.