-2

I have number_list ['3', '.', '8', '5', '2'] and try to transform back to 3.852 by

>>> 3*10**(0) + 8*10**(-1) + 5*10**(-2) + 2*10**(-3)
3.8519999999999994

Why i got 3.8519999999999994, not 3.852 ? How to fix it ? Part of the calculation works independently.

>>> 3*10**(0)
3
>>> 8*10**(-1)
0.8
>>> 5*10**(-2)
0.05
>>> 2*10**(-3)
0.002
Alan
  • 3
  • 2
  • 1
    See also: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). It's not clear if you are asking why, or just want to solve the problem, which is probably better solved with `float(''.join(['3', '.', '8', '5', '2']))` – Mark Mar 15 '22 at 04:25
  • The modules "decimal" and "fractions" provide other number implementations which may help here. – Michael Butscher Mar 15 '22 at 04:29

2 Answers2

0

If you want the results within 3 decimal points you can use a python built in function round

expression = 3*10**(0) + 8*10**(-1) + 5*10**(-2) + 2*10**(-3)
round(expression, 3)
Tanvir Ahmed
  • 357
  • 2
  • 15
0

You can solve this using string concatenation and parsing the output string.

Example:

number_list = ['3', '.', '8', '5', '2']
parsed_number = float("".join(number_list))
print(parsed_number)
# Output: 3.852
Hultan
  • 1,409
  • 1
  • 15
  • 28