Decimal to Fraction Program in java

Question:

Bobby is in her 2nd grade and has just started to learn about fractions. Whenever she comes across a decimal number she is curious to know the equivalent fraction for that number. Help her to convert a decimal number into a fraction. Write a program that accepts a decimal number and prints the fraction equivalent in the simplified/reduced form.

Sample input1

12.5

Sample output 1(Improper Fraction- where the numerator is greater than denominator)

Fraction: 25/2

Sample input 2

0.625

Sample output 2(Proper Fraction- where the numerator is lesser than denominator)

Fraction: 5/8

Sample input 3

3

Sample output 3

Input a decimal number

CODE:

import java.util.*;
public class Main 
{
    public static void fraction(double x)
    {   Main obj=new Main();
        String a=""+x;
        String splits[]=a.split("\\.");
        int b=splits[1].length();
        int denominator=(int)Math.pow(10, b);
        int numerator=(int)(x*denominator);
        
        int gcd=obj.getGCD(numerator, denominator);
        
        String fraction=""+numerator/gcd+"/"+denominator/gcd;
       System.out.println("Fraction: "+fraction);
    }
    
    int getGCD(int n1, int n2)
    {
        if(n2==0)
        {
            return n1;
        }
        
        return getGCD(n2, n1%n2);
    }
    
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
        double a=sc.nextDouble();
        if(a==(int)(a))
        {
            System.out.println("Input a decimal number");
        }
        else{
            fraction(a);
        }
    }
}

Leave a Comment

Scroll to Top