Skip to main content

How to convert a number to a fraction in Python

How to convert a number to a fraction in Python.

Introduction

In Python, you can convert a decimal number into a fraction using the fractions module. This module provides a Fraction class that allows you to work with fractions easily. This tutorial will guide you through the process of converting a number to a fraction step by step, providing multiple code examples where applicable.

Step 1: Import the fractions module

To begin, you need to import the fractions module. This module is part of the Python standard library, so you don't need to install any external packages. Here's the code:

import fractions

Step 2: Create a Fraction object

Now that you have imported the fractions module, you can create a Fraction object. The Fraction class takes two arguments: the numerator and the denominator. You can pass the decimal number as the numerator and 1 as the denominator. Here's an example:

fraction = fractions.Fraction(0.5, 1)

Step 3: Simplify the fraction (optional)

If you want to simplify the fraction, you can call the fraction.simplify() method. This method reduces the fraction to its simplest form. Here's an example:

fraction.simplify()

Step 4: Retrieve the fraction components

To access the numerator and denominator of the fraction, you can use the fraction.numerator and fraction.denominator attributes, respectively. Here's an example:

numerator = fraction.numerator
denominator = fraction.denominator

Step 5: Convert the fraction to a string (optional)

If you want to convert the fraction to a string representation, you can use the fraction.__str__() method or the str(fraction) function. Here's an example:

fraction_str = str(fraction)

Step 6: Print the fraction

To display the fraction, you can use the print() function. Here's an example:

print(fraction)

Putting it all together:

Here's the complete code that converts a number to a fraction and prints it:

import fractions

decimal_number = 0.5
fraction = fractions.Fraction(decimal_number, 1)

fraction.simplify()

numerator = fraction.numerator
denominator = fraction.denominator

fraction_str = str(fraction)

print(fraction)

In this tutorial, you learned how to convert a decimal number to a fraction in Python using the fractions module. By following the step-by-step instructions and code examples, you can easily convert any decimal number to its corresponding fraction representation.