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 (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (117) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (752) Python Coding Challenge (225) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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