Zak Stucke
Zak Stucke

Reputation: 452

Turning Decimal type numbers into string type exactly

How do I turn a decimal from the decimal module into a string exactly so I can loop through in a list? Or is there another method that would work better when trying to work out the number of decimal places something is accurate to (ignoring trailing zeros at the end).

import decimal
number = decimal.Decimal('0.00000001')

print(str(number))
>>'1E-8'

instead I want:

print(str(number))
>> '0.00000001'

edit: I don't need .format to print it I need to loop through each digit in a for loop. Thanks

Upvotes: 0

Views: 163

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96172

If you simply want the number of decimal places in the number (ignoring trailing zeros) just use decimal.Decimal.as_tuple, so:

In [48]: number = decimal.Decimal('0.00000001')
    ...:

In [49]: number.as_tuple()
Out[49]: DecimalTuple(sign=0, digits=(1,), exponent=-8)

In [50]: abs(number.as_tuple().exponent)
Out[50]: 8

Note, to be safe, you probably need to .normalize:

In [57]: number = decimal.Decimal('3.0000')

In [58]: number.as_tuple()
Out[58]: DecimalTuple(sign=0, digits=(3, 0, 0, 0, 0), exponent=-4)

In [59]: number.normalize().as_tuple().exponent
Out[59]: 0

So...

In [65]: new_number = number.log10()

In [66]: new_number
Out[66]: Decimal('0.4771212547196624372950279033')

In [67]: abs(new_number.normalize().as_tuple().exponent)
Out[67]: 28

In [68]: len('4771212547196624372950279033')
Out[68]: 28

Upvotes: 2

Matt
Matt

Reputation: 285

Use format

print('{0:f}'.format(number))

Upvotes: 2

Related Questions