Saturday, 6 January 2024

Day 173 : Convert Decimal to Fraction in Python

 


from fractions import Fraction

# Convert decimal to fraction

decimal_number = input("Enter a Decimal Number:")

fraction_result = Fraction(decimal_number).limit_denominator()

print(f"Decimal: {decimal_number}")

print(f"Fraction: {fraction_result}")

#clcoding.com for free code visit


Explanation : 

Let's break down the code step by step:

from fractions import Fraction

This line imports the Fraction class from the fractions module. The Fraction class is used to represent and perform operations with rational numbers.

# Convert decimal to fraction

decimal_number = input("Enter a Decimal Number:")

This line prompts the user to enter a decimal number by using the input function. The entered value is stored in the variable decimal_number.

fraction_result = Fraction(decimal_number).limit_denominator()

Here, the entered decimal_number is converted to a Fraction object using the Fraction class. The limit_denominator() method is then called to limit the denominator of the fraction to a reasonable size.

print(f"Decimal: {decimal_number}")

print(f"Fraction: {fraction_result}")

These lines print the original decimal number entered by the user and the corresponding fraction.

#clcoding.com for free code visit

This line is a comment and is not executed as part of the program. It's just a comment providing a website link.

So, when you run this code, it will prompt you to enter a decimal number, convert it to a fraction, and then print both the original decimal and the corresponding fraction. The limit_denominator() method is used to present the fraction in a simplified form with a limited denominator.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (893) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses