Convert given Float value to equivalent Fraction

Given a floating-point number in the form of a string N, the task is to convert the given floating-point number into fractions.

Enclosed sequence of digits in “()” in the floating-point representation expresses recurrence in the decimal representation. 
For example, 1.(6) represents 1.666…. 
 

Examples:

Input: N = “1.5”
Output: 3 / 2
Explanation:
The value of 3 / 2 will be equal to 1.5

Input: N = “1.(6)”
Output: 5 / 3
Explanation:
The value of 5 / 3 will be equal to 1.666… which is represented as 1.(6).



Approach: The idea is to use the Greatest Common Divisor of two numbers and some mathematical equations to solve the problem. Follow the below steps to solve the problem:

  • Let there be x numbers after the decimal except for the recurring sequence.
  • If there is no recurring sequence then multiply the given number with 10x and let the GCD of 10x and the resultant number be g. Print resultant divided by g as the numerator and 10x divided by g as the denominator.

For example, if N = “1.5” then x = 1.
Multiplying N with 10, the resultant will be 15 and the GCD of 10 and 15 is 3.
Therefore, print 15/3 = 5 as the numerator and 10/5 as the denominator.

  • If the recurrence sequence is present, then multiply N with 10x. For example, if N = 23.98(231) multiply it with N*(102).
  • Let the total number of digits in a sequence be y. For 102*N = 2398.(231), y becomes 3.
  • Multiply 10y with N*10x. For 102*N = 2398.(231), multiply it with 103 i.e., 102*N*103 = 2398231.(231).
  • Now, subtract, N*10y+x with N*10x and let the result be M. For the above example, 102*N*(103-1) = 2395833.
  • Therefore, N = M / ((10x)*(10y – 1)). For the above example, N = 2395833 / 999000.
  • Find the GCD of M and ((10x)*(10y – 1)) and print M / gcd as the numerator and ((10x)*(10y – 1)) as the denominator.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert the floating
// values into fraction
void findFraction(string s)
{
    // Initialize variables
    string be_deci = "",
           af_deci = "",
           reccu = "";
 
    bool x = true, y = false,
         z = false;
 
    // Traverse the floating string
    for (int i = 0; i < s.size(); ++i) {
 
        // Check if decimal part exist
        if (s[i] == '.') {
            x = false;
            y = true;
            continue;
        }
 
        // Check if recurrence
        // sequence exist
        if (s[i] == '(') {
            z = true;
            y = false;
            continue;
        }
 
        // Retrive decimal part
        // and recurrence resquence
        if (x)
            be_deci += s[i];
 
        if (y)
            af_deci += s[i];
 
        if (z) {
 
            // Traverse the string
            for (; i < s.size()
                   && s[i] != ')';
                 ++i)
                reccu += s[i];
            break;
        }
    }
 
    // Convert string to integer
    int num_be_deci = stoi(be_deci);
    int num_af_deci = 0;
 
    // If no recurrence sequence exist
    if (af_deci.size() != 0)
        num_af_deci = stoi(af_deci);
 
    // Initialize numerator & denominator
    int numr = num_be_deci
                   * pow(10, af_deci.size())
               + num_af_deci;
 
    int deno = pow(10, af_deci.size());
 
    // No reccuring term
    if (reccu.size() == 0) {
        int gd = __gcd(numr, deno);
 
        // Print the result
        cout << numr / gd << " / "
             << deno / gd;
    }
 
    // If reccuring term exist
    else {
 
        // Convert reccuring term to integer
        int reccu_num = stoi(reccu);
 
        // reccu.size() is num of
        // digit in reccur term
        int numr1
            = numr
                  * pow(10, reccu.size())
              + reccu_num;
 
        int deno1 = deno
                    * pow(10, reccu.size());
 
        // eq 2 - eq 1
        int res_numr = numr1 - numr,
            res_deno = deno1 - deno;
 
        int gd = __gcd(res_numr,
                       res_deno);
 
        // Print the result
        cout << res_numr / gd << " / "
             << res_deno / gd;
    }
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "23.98(231)";
 
    // Function Call
    findFraction(str);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Recursive function to return
// gcd of a and b 
static int __gcd(int a, int b) 
    return b == 0 ? a : __gcd(b, a % b);    
}
 
// Function to convert the floating
// values into fraction
static void findFraction(String s)
{
     
    // Initialize variables
    String be_deci = "",
           af_deci = "",
             reccu = "";
 
    boolean x = true, y = false,
            z = false;
 
    // Traverse the floating String
    for(int i = 0; i < s.length(); ++i)
    {
         
        // Check if decimal part exist
        if (s.charAt(i) == '.')
        {
            x = false;
            y = true;
            continue;
        }
 
        // Check if recurrence
        // sequence exist
        if (s.charAt(i)  == '(')
        {
            z = true;
            y = false;
            continue;
        }
 
        // Retrive decimal part
        // and recurrence resquence
        if (x)
            be_deci += s.charAt(i);
 
        if (y)
            af_deci += s.charAt(i);
 
        if (z)
        {
             
            // Traverse the String
            for(; i < s.length() && s.charAt(i) != ')';
                  ++i)
                reccu += s.charAt(i);
                 
            break;
        }
    }
 
    // Convert String to integer
    int num_be_deci = Integer.valueOf(be_deci);
    int num_af_deci = 0;
 
    // If no recurrence sequence exist
    if (af_deci.length() != 0)
        num_af_deci = Integer.valueOf(af_deci);
 
    // Initialize numerator & denominator
    int numr = num_be_deci *
               (int)Math.pow(10, af_deci.length()) +
               num_af_deci;
 
    int deno = (int)Math.pow(10, af_deci.length());
 
    // No reccuring term
    if (reccu.length() == 0)
    {
        int gd = __gcd(numr, deno);
 
        // Print the result
        System.out.print(numr / gd + " / " +
                         deno / gd);
    }
 
    // If reccuring term exist
    else
    {
         
        // Convert reccuring term to integer
        int reccu_num = Integer.valueOf(reccu);
 
        // reccu.size() is num of
        // digit in reccur term
        int numr1 = numr *
                    (int)Math.pow(10, reccu.length()) +
                    reccu_num;
 
        int deno1 = deno * (int) Math.pow(
                    10, reccu.length());
 
        // eq 2 - eq 1
        int res_numr = numr1 - numr,
            res_deno = deno1 - deno;
 
        int gd = __gcd(res_numr,
                       res_deno);
 
        // Print the result
        System.out.print(res_numr / gd + " / " +
                         res_deno / gd);
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String str
    String str = "23.98(231)";
 
    // Function Call
    findFraction(str);
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
from math import gcd
 
# Function to convert the floating
# values into fraction
def findFraction(s):
     
    # Initialize variables
    be_deci = ""
    af_deci = ""
    reccu = ""
 
    x = True
    y = False
    z = False
 
    # Traverse the floating string
    for i in range(len(s)):
         
        # Check if decimal part exist
        if (s[i] == '.'):
            x = False
            y = True
            continue
 
        # Check if recurrence
        # sequence exist
        if (s[i] == '('):
            z = True
            y = False
            continue
 
        # Retrive decimal part
        # and recurrence resquence
        if (x):
            be_deci += s[i]
 
        if (y):
            af_deci += s[i]
 
        if (z):
 
            # Traverse the string
            while i < len(s) and s[i] != ')':
                reccu += s[i]
                i += 1
                 
            break
 
    # Convert to integer
    num_be_deci = int(be_deci)
    num_af_deci = 0
 
    # If no recurrence sequence exist
    if len(af_deci) != 0:
        num_af_deci = int(af_deci)
 
    # Initialize numerator & denominator
    numr = (num_be_deci *
            pow(10, len(af_deci)) +
            num_af_deci)
 
    deno = pow(10, len(af_deci))
 
    # No reccuring term
    if len(reccu) == 0:
        gd = gcd(numr, deno)
 
        # Print the result
        print(numr // gd, "/", deno // gd)
 
    # If reccuring term exist
    else:
 
        # Convert reccuring term to integer
        reccu_num = int(reccu)
 
        # reccu.size() is num of
        # digit in reccur term
        numr1 = (numr * pow(10, len(reccu)) +
                 reccu_num)
 
        deno1 = deno * pow(10, len(reccu))
 
        # eq 2 - eq 1
        res_numr = numr1 - numr
        res_deno = deno1 - deno
 
        gd = gcd(res_numr, res_deno)
 
        # Print the result
        print(res_numr // gd, " / ",
              res_deno // gd)
 
# Driver Code
if __name__ == '__main__':
     
    # Given str
    str = "23.98(231)"
 
    # Function Call
    findFraction(str)
     
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
     
// Recursive function to return
// gcd of a and b 
static int __gcd(int a, int b) 
    return b == 0 ? a : __gcd(b, a % b);    
}
 
// Function to convert the floating
// values into fraction
static void findFraction(String s)
{
     
    // Initialize variables
    String be_deci = "",
           af_deci = "",
             reccu = "";
 
    bool x = true, y = false,
                   z = false;
 
    // Traverse the floating String
    for(int i = 0; i < s.Length; ++i)
    {
         
        // Check if decimal part exist
        if (s[i] == '.')
        {
            x = false;
            y = true;
            continue;
        }
 
        // Check if recurrence
        // sequence exist
        if (s[i]  == '(')
        {
            z = true;
            y = false;
            continue;
        }
 
        // Retrive decimal part
        // and recurrence resquence
        if (x)
            be_deci += s[i];
 
        if (y)
            af_deci += s[i];
 
        if (z)
        {
             
            // Traverse the String
            for(; i < s.Length && s[i] != ')';
                  ++i)
                reccu += s[i];
                 
            break;
        }
    }
 
    // Convert String to integer
    int num_be_deci = Int32.Parse(be_deci);
    int num_af_deci = 0;
 
    // If no recurrence sequence exist
    if (af_deci.Length != 0)
        num_af_deci = Int32.Parse(af_deci);
 
    // Initialize numerator & denominator
    int numr = num_be_deci *
               (int)Math.Pow(10, af_deci.Length) +
               num_af_deci;
 
    int deno = (int)Math.Pow(10, af_deci.Length);
 
    // No reccuring term
    if (reccu.Length == 0)
    {
        int gd = __gcd(numr, deno);
 
        // Print the result
        Console.Write(numr / gd + " / " +
                      deno / gd);
    }
 
    // If reccuring term exist
    else
    {
         
        // Convert reccuring term to integer
        int reccu_num = Int32.Parse(reccu);
 
        // reccu.Count is num of
        // digit in reccur term
        int numr1 = numr *
                    (int)Math.Pow(10, reccu.Length) +
                    reccu_num;
 
        int deno1 = deno * (int)Math.Pow(
                    10, reccu.Length);
 
        // eq 2 - eq 1
        int res_numr = numr1 - numr,
            res_deno = deno1 - deno;
 
        int gd = __gcd(res_numr,
                       res_deno);
 
        // Print the result
        Console.Write(res_numr / gd + " / " +
                      res_deno / gd);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String str
    String str = "23.98(231)";
 
    // Function Call
    findFraction(str);
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

798611 / 33300











 

Time Complexity: O(log10N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.