Convert Decimal to Fraction [7 Programming Languages]


Deepak Prasad

Tips and Tricks

Converting decimals to fractions is a fundamental concept in mathematics that finds applications in various fields, such as engineering, finance, and data science. Understanding "how to convert decimal to fraction" can simplify many complex calculations and also provide a more accurate representation of numerical data. This article aims to equip you with multiple methods for achieving this conversion across various popular programming languages. Whether you're a student looking to master this concept for your math classes or a professional who needs this skill for data manipulation, you'll find this guide extremely useful.

So let's dive in and explore the different ways on how to convert decimal to fraction.

In this tutorial we will cover How to convert decimal to fraction using following programming languages

  • Java
  • Python
  • JavaScript
  • C++
  • Ruby
  • C#
  • R

 

Convert Decimal to Fraction in Python

Python offers powerful built-in libraries that make it effortless to convert decimal to fraction. Leveraging these pre-existing modules can save you a lot of time and offer a high level of accuracy. If you've been wondering "how to convert decimal to fraction" using Python, these libraries are the first place to look.

Here are two simple examples to convert decimal to fraction in Python.

Using the fractions library: The fractions library in Python can automatically convert float to fraction.

from fractions import Fraction

decimal_number = 0.75
fraction = Fraction(decimal_number).limit_denominator()
print(f"The fraction is {fraction}")

This would output The fraction is 3/4.

Custom Function: You can also create a custom function that employs basic math to convert decimal to fraction.

def decimal_to_fraction(decimal, tolerance=1e-6):
    numerator = 1
    while abs(decimal - round(decimal)) > tolerance:
        decimal *= 10
        numerator *= 10
    denominator = round(decimal)
    return f"{denominator}/{numerator}"

decimal_number = 0.75
fraction = decimal_to_fraction(decimal_number)
print(f"The fraction is {fraction}")

This would also output The fraction is 3/4.

 

Convert Decimal to Fraction in Java

In Java, converting a decimal to a fraction isn't as straightforward as in Python, mainly because Java's standard library doesn't include a built-in fraction class. However, there are third-party libraries like Apache Commons Math that provide such functionality. You can also implement a simple custom method for the conversion.

Using Apache Commons Math Library: This library offers a Fraction class that can be used to convert decimal to fraction.

import org.apache.commons.math3.fraction.Fraction;

public class DecimalToFraction {
    public static void main(String[] args) {
        double decimalNumber = 0.75;
        Fraction fraction = new Fraction(decimalNumber);
        System.out.println("The fraction is " + fraction.getNumerator() + "/" + fraction.getDenominator());
    }
}

When you run this, it will output "The fraction is 3/4".

Custom Method: If you'd rather not use an external library, you can write a function yourself.

public class DecimalToFraction {
    public static void main(String[] args) {
        double decimalNumber = 0.75;
        String fraction = decimalToFraction(decimalNumber, 1e-6);
        System.out.println("The fraction is " + fraction);
    }

    public static String decimalToFraction(double decimal, double tolerance) {
        double numerator = 1;
        while (Math.abs(decimal - Math.round(decimal)) > tolerance) {
            decimal *= 10;
            numerator *= 10;
        }
        int denominator = (int) Math.round(decimal);
        return denominator + "/" + (int)numerator;
    }
}

This would also output "The fraction is 3/4".

 

Convert Decimal to Fraction in JavaScript

In JavaScript, converting a decimal to a fraction can be achieved through various methods, depending on the level of precision you require and the libraries you are willing to use.

Using Fraction.js Library: One of the most reliable ways to convert decimal to fraction is by using the Fraction.js library, which can be installed via npm or included directly in your HTML.

const Fraction = require('fraction.js');

let decimalNumber = 0.75;
let fraction = new Fraction(decimalNumber);
console.log(`The fraction is ${fraction.n}/${fraction.d}`);

Custom Function: If you don't want to rely on external libraries, you can also create a custom function to perform the conversion

function decimalToFraction(decimal, tolerance = 1e-6) {
    let numerator = 1;
    while (Math.abs(decimal - Math.round(decimal)) > tolerance) {
        decimal *= 10;
        numerator *= 10;
    }
    let denominator = Math.round(decimal);
    return `${denominator}/${numerator}`;
}

let decimalNumber = 0.75;
let fraction = decimalToFraction(decimalNumber);
console.log(`The fraction is ${fraction}`);

 

Convert Decimal to Fraction in C++

In C++, converting a decimal to a fraction is often done using standard libraries or custom functions, depending on your project's needs.

Using the Boost Rational Library: One of the most effective methods for dealing with fractions in C++ is the Boost Rational Library. After installing the Boost libraries, you can include the Boost Rational header and use it to convert decimal to fraction.

#include <boost/rational.hpp>

int main() {
    boost::rational<int> fraction(75, 100);
    fraction = fraction / boost::gcd(fraction.numerator(), fraction.denominator());

    std::cout << "The fraction is: " << fraction.numerator() << "/" << fraction.denominator() << std::endl;
}

Custom Function: Alternatively, you can write a custom function for this purpose. The simplest approach might involve finding the greatest common divisor (GCD) to reduce the fraction to its simplest form.

#include <iostream>

int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

int main() {
    int numerator = 75, denominator = 100;
    int commonGCD = gcd(numerator, denominator);

    numerator /= commonGCD;
    denominator /= commonGCD;

    std::cout << "The fraction is: " << numerator << "/" << denominator << std::endl;
}

 

Convert Decimal to Fraction in Ruby

In Ruby, the language provides a built-in Rational class that allows for the conversion of decimals to fractions easily. This class is a part of Ruby's standard library and is specifically designed to work with rational numbers, ensuring that you can perform accurate mathematical operations without the imprecision that can come from floating-point arithmetic.

decimal_number = 0.75
fraction = Rational(decimal_number)

puts "The fraction is #{fraction}"  # Output will be "The fraction is 3/4"

Or, if you're working with a string representation of a decimal:

decimal_str = "0.75"
fraction = Rational(decimal_str)
puts fraction  # Output will be "3/4"

You can also manually write a function that employs a mathematical algorithm, such as the Euclidean algorithm to find the Greatest Common Divisor (GCD). Below is an example that utilizes the Euclidean algorithm to convert decimal to fraction:

gcd <- function(a, b) {
  while (b != 0) {
    temp <- b
    b <- a %% b
    a <- temp
  }
  return(a)
}

decimalToFraction <- function(decimal) {
  denominator <- 10 ** (nchar(sub(".*\\.", "", as.character(decimal))))
  numerator <- decimal * denominator
  
  common_gcd <- gcd(numerator, denominator)
  
  numerator <- numerator / common_gcd
  denominator <- denominator / common_gcd
  
  return(paste(numerator, "/", denominator, sep=""))
}

# Example usage
result <- decimalToFraction(0.75)
print(result)  # Output: "3/4"

This function first converts the decimal to a "common fraction" (e.g., 0.75 to 75/100), then finds and applies the GCD to simplify it.

 

Convert Decimal to Fraction in C#

In C#, there are multiple ways to convert decimal to fraction, offering you flexibility depending on your project's specific requirements. Unlike some languages, C# doesn't have a built-in Rational or Fraction class. However, you can leverage other features of the language, including third-party libraries, to accomplish this task effectively.

using System;

public class Program
{
    public static void Main()
    {
        decimal decimalNumber = 0.75M;
        int denominator = 10000;
        
        int numerator = (int)(decimalNumber * denominator);
        
        int gcd = GCD(numerator, denominator);
        
        Console.WriteLine($"The fraction is {numerator / gcd}/{denominator / gcd}");
    }
    
    public static int GCD(int a, int b)
    {
        while (b != 0)
        {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}

Here, GCD is a helper function that calculates the greatest common divisor, which is then used to simplify the fraction.

In C#, you can use the Fraction structure from the System.Windows namespace (requires adding a reference to WindowsBase.dll):

using System;
using System.Windows;  // For Fraction structure

class Program
{
    static void Main()
    {
        double decimalNumber = 0.75;
        Fraction fraction = new Fraction(decimalNumber);
        Console.WriteLine(fraction);  // Output depends on the Fraction implementation
    }
}

Note: The Fraction structure is more commonly used in specific areas like Windows Presentation Foundation (WPF), and its direct usage may vary. This is more of an illustrative example, and in practical applications, you might write a custom function or use third-party libraries.

 

Convert Decimal to Fraction in R

In R, you can use built-in functionality or libraries like MASS to convert decimal to fraction. R has the ability to handle rational numbers in the form of fractions by using the fractions() function from the MASS package. Here's a simple example:

First, install the MASS package if you haven't:

install.packages("MASS")

Then, load the package and use the fractions function:

library(MASS)

decimal_number <- 0.75
fraction <- fractions(decimal_number)

print(paste("The fraction is", fraction))

This will output:

[1] "The fraction is 3/4"

 

Summary

In conclusion, converting a decimal to a fraction can be achieved in various programming languages using built-in methods or libraries. While some languages like Python offer straightforward, built-in functions, others may require importing a special package or implementing a custom function. The methods may vary, but the goal remains the same: to convert decimal numbers into their fractional counterparts for more precise computations or specific requirements.

  • Python's fractions module makes it very simple to convert decimal to fractions.
  • Java has the BigDecimal class which can be leveraged for this task.
  • JavaScript, lacking built-in support, could use libraries like math.js for precise calculations.
  • C++ programmers can either use Boost libraries or custom functions.
  • Ruby offers the Rational class to handle rational numbers efficiently.
  • C# users can use the built-in Fraction structure or third-party libraries.
  • In R, the fractions() function from the MASS package offers a straightforward solution.

 

Additional Resources

 

Views: 11

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

GoLinuxCloud Logo


We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Programming Languages

JavaScript

Python

Golang

Node.js

Java

Laravel