Uncanny python math operations | Sololearn: Learn to code for FREE!
+ 1

Uncanny python math operations

When I'm doing math or division operations in python I'll often get numbers like '297.40000000000003', how do I prevent this without using round() to simply the number to 297.4?

5th Jul 2019, 8:06 AM
Branam
Branam - avatar
4 Respuestas
+ 3
Unless you are going to perfom type coersion, you will not be able to _prevent_ default prescison. So, either round (without coersion) or string formatting.
5th Jul 2019, 8:42 AM
strawdog
strawdog - avatar
+ 3
If you need more precision, you can check out the decimal library. It works also on sololearn. https://docs.python.org/3/library/decimal.html
5th Jul 2019, 6:52 PM
Tibor Santa
Tibor Santa - avatar
+ 1
Branam , You can sometimes prevent the error by rearranging your formula so division happens last. For example, x = a / b * c # more likely to err x = a * c / b # less likely to err
14th Nov 2023, 1:57 AM
Rain
Rain - avatar
0
fairly simple to do yourself n = input() n_rounded = "" for i,j in enumerate(n): n_rounded += j try: if not int(j) and n.index(j,i,i+1)>n.index("."): break except: pass
11th Jul 2019, 5:02 AM
Choe
Choe - avatar