0

How to change decimel to fraction

Is there any easy function or method by which a decimel can easily be turned into fraction or vice versa in python? Like a = 2.3333333 a.method() or func(a) and the return will be 2 1/3 and vice versa.

5th Sep 2020, 1:34 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
4 Respuestas
+ 4
You can use the Fraction module Ex: >>>from fractions import Fraction >>>Fraction(0.2) However, it would end up with strange very long numbers for both numerator and denominator: Fraction(3602879701896397, 18014398509481984) To avoid this, add .limit_denominator() to your expression. Ex: >>>Fraction(0.2).limit_denominator() Fraction(1, 5) Add str method to make the result more readable. Ex: >>>str(Fraction(0.2).limit_denominator()) '1/5' >>>str(Fraction(0.2)) '3602879701896397/18014398509481984' Here is what I found: • https://stackoverflow.com/questions/23344185/how-to-convert-a-decimal-number-into-fractionhttps://www-geeksforgeeks-org.cdn.ampproject.org/v/s/www.geeksforgeeks.org/fraction-module-JUMP_LINK__&&__python__&&__JUMP_LINK/amp/?amp_js_v=a2&amp_gsa=1&usqp=mq331AQFKAGwASA%3D#aoh=15993144492139&referrer=https%3A%2F%2Fwww.google.com&amp_tf=%D0%94%D0%B6%D0%B5%D1%80%D0%B5%D0%BB%D0%BE%3A%20%251%24s&ampshare=https%3A%2F%2Fwww.geeksforgeeks.org%2Ffraction-module-python%2Fhttps://www.programiz.com/python-programming/numbers
5th Sep 2020, 2:39 PM
Феникс
Феникс - avatar
+ 1
Here is a quick example, it only does decimal to fraction, and its a little ugly. https://code.sololearn.com/cPwm7N6vW80M/#py
5th Sep 2020, 2:48 PM
Steven M
Steven M - avatar
+ 1
Thanks Феникс and Steven M. Really helpful. Now i gonna practise em all
5th Sep 2020, 3:34 PM
Mir Abir Hossain
Mir Abir Hossain - avatar
+ 1
Mir Abir Hossain My pleasure! 😉
5th Sep 2020, 4:01 PM
Феникс
Феникс - avatar