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.
4 odpowiedzi
+ 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-fraction
• https://www-geeksforgeeks-org.cdn.ampproject.org/v/s/www.geeksforgeeks.org/fraction-module-JUMP_LINK__&&__python__&&__JUMP_LINK/amp/?amp_js_v=a2&_gsa=1&usqp=mq331AQFKAGwASA%3D#aoh=15993144492139&referrer=https%3A%2F%2Fwww.google.com&_tf=%D0%94%D0%B6%D0%B5%D1%80%D0%B5%D0%BB%D0%BE%3A%20%251%24s&share=https%3A%2F%2Fwww.geeksforgeeks.org%2Ffraction-module-python%2F
• https://www.programiz.com/python-programming/numbers
+ 1
Here is a quick example, it only does decimal to fraction, and its a little ugly.
https://code.sololearn.com/cPwm7N6vW80M/#py
+ 1
Mir Abir Hossain
My pleasure! 😉