简体   繁体   中英

Can python decimal preserve decimal formatting

Python decimal module is converting an exact encoded string decimal value into e notation, which is rather unexpected given the module documentation.

>>> d = decimal.Decimal('0.00000039')
>>> d
Decimal('3.9E-7')

Also after trying to quantize the value the output stays the same:

>>> print d.quantize(decimal.Decimal('0.00000001'))
3.9E-7

How can I prevent this from happening and just keep the source formatting without having to do format conversions. Please also feel free to recommend other stable and reliable modules for working with exact decimals.

You have full control over how the value is displayed, using either '%f' or {:f} string formatting instructions. For example:

>>> d = decimal.Decimal('.0000000037')
>>> print('{:f}'.format(d))
0.0000000037
>>> print('{:e}'.format(d))
3.7e-9
>>> print('{:g}'.format(d))
3.7e-9
>>> 

Here are other ways to display the value:

In [4]: d = decimal.Decimal('.0000000037')

In [5]: d
Out[5]: Decimal('3.7E-9')

In [6]: str(d)
Out[6]: '3.7E-9'

In [7]: repr(d)
Out[7]: "Decimal('3.7E-9')"

In [8]: '{:f}'.format(d)
Out[8]: '0.0000000037'

If you want to customize the default representations of Decimal , you can derive a class from decimal.Decimal and override .__str__() and .__repr__ .

import decimal

class Decimal(decimal.Decimal):
    def __str__(self):
        return "'" + decimal.Decimal.__format__(self, 'f') + "'"
    def __repr__(self):
        return self.__str__()

Usage:

>>> import x
>>> d = x.Decimal('0.0000000039')
>>> d
'0.0000000039'
>>> [d]
['0.0000000039']

Note that this will always use your specified formatting style, even if the original text was in a different format.

>>> e = x.Decimal('6.022140857e23')
>>> e
'602214085700000000000000'
>>> [e]
['602214085700000000000000']
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM