-1

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.

Tom Liu
  • 35
  • 3

2 Answers2

0

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
Keldorn
  • 1,980
  • 15
  • 25
0

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.

roPe
  • 26
  • 6
  • `round()` might be a good option. I just want to find a way to avoid floating-point issue. – Tom Liu May 14 '22 at 08:45
  • Why use `round()` instead of f-strings? https://docs.python.org/3/reference/lexical_analysis.html#f-strings – Keldorn May 14 '22 at 09:06
  • I just assumed that OP would want to keep return value as a float instead of string. – roPe May 14 '22 at 09:32