'How to write a simple code to do float calculation in Python?
I would like to write a code for this calculation:
3.3+4.8*6-4/2
Here is my code:
from decimal import *
a = Decimal('3.3') + Decimal('4.8') * 6
b = 4 / 2
c = a - Decimal(str(b))
print(c)
The above code can give the right answer: 30.1. But I think it is too complex and there should be a simpler solution. Can anyone give a simplified code? Thanks.
Solution 1:[1]
From your provided calculation it is not clear if you will use different variables in it or if you want to evaluate just this one particular equation. If you want to compute just this equation, compute "(3.3 + 4.8 * 6.0) - 2.0" because you do not really need calculator for 4/2. So simply:
result = 3.3 + 4.8 * 6.0 - 2.0
print(round(result, 2)) #round() to "render" floating-point error
But if it will be used many times for different variables, you should define a function, e.g. (suppose all numbers in the equation are variables):
def eq_evaluation(a, b, c, d, e):
return round((a + b * c - d / e), 2)
Also wildcard import (from package import *) is not a best practice in python. See for example: This question about it.
Solution 2:[2]
Assuming python 3:
print(3.3+4.8*6-4/2)
# 30.099999999999994
print('{:.2f}'.format(3.3+4.8*6-4/2))
# 30.10
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | roPe |
| Solution 2 |
