0

When I append a Decimal(x) value to an array I would like to just get the number but it also includes the Decimal() function call at the start of the element.

Code:

array = []
a = Decimal(0.000005342)
array.append(a)
print(array)

Output:

[Decimal('0.0000053419999999999998450852904674501786530527169816195964813232421875')]
martineau
  • 119,623
  • 25
  • 170
  • 301
djluc101
  • 1
  • 1
  • 2
    That *is* the number. Also note you shouldn't create `Decimal`s from floats - as you can see, you lose precision over `Decimal('0.000005342')`. – jonrsharpe Apr 07 '21 at 15:25
  • The reason to use a string is because floating point on computers is approximate. See question [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) Also note that your variable named `array` is a Python **`list`**, not an array. – martineau Apr 07 '21 at 15:33

1 Answers1

1

What you are seeing printed out is the repr() of the list. This is a representation that when printed out and executed should result in an equal object. To view the str of the object, you have to manually call str on the Decimal instances:

print(", ".join(str(d) for d in array))
MegaIng
  • 7,361
  • 1
  • 22
  • 35
  • It should be noted that your solution is still going to print `0.0000053419999999999998450852904674501786530527169816195964813232421875` because of the way the `Decimal` instance is being created. – martineau Apr 07 '21 at 15:39