-4

I have a JSON output that is Decimal('142.68500203').

I can use str() to get a string which is "142.68500203". But I want to get a number output which is 142.68500203.

How to make the conversion in Python?

alextc
  • 3,206
  • 10
  • 63
  • 107
  • what is that `Decimal`? have you tried call float? – marcadian Jun 17 '16 at 06:54
  • `float(…)` – Of course `str()` gives you a string, that’s the whole point. If you want a different type, you need to use that type’s converter. – poke Jun 17 '16 at 06:54
  • 3
    _Why_ do you want to convert it? The reason that the JSON output is a Decimal is that you don't lose any precision that way. A float might not be able to store the number exactly. – RemcoGerlich Jun 17 '16 at 06:59
  • 3
    Possible duplicate of [How to convert decimal string in python to a number?](http://stackoverflow.com/questions/6794779/how-to-convert-decimal-string-in-python-to-a-number) – SiHa Jun 17 '16 at 07:00

2 Answers2

3

It depends what you mean by "number", it could be argued that Decimal is a number class. If you mean into an object of float class then:

from decimal import Decimal

x = Decimal('142.68500203')

y = float(x)

print x, y

Gives:

142.68500203 142.68500203

But beware! There are good reasons for using Decimal, read the Decimal documentation before deciding you want float.

cdarke
  • 42,728
  • 8
  • 80
  • 84
1

It is quite easy:

float("142.68500203")
Ian
  • 1,688
  • 18
  • 35