Decimal to Fraction Program in java

In this post, we will learn Decimal to Fraction Program in java Programming language.


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


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

Fraction: 25/2

Sample input 2


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

Fraction: 5/8

Sample input 3


Sample output 3

Input a decimal number


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)
            return n1;
        return getGCD(n2, n1%n2);
    public static void main (String[] args) {
        Scanner sc=new Scanner(;
        double a=sc.nextDouble();
            System.out.println("Input a decimal number");
Sharing Is Caring

Leave a Comment