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

100 Python Programs for Beginner (56) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (935) Python Coding Challenge (368) Python Quiz (27) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

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