简体   繁体   English

python十进制可以保留十进制格式吗

[英]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. Python十进制模块正在将精确编码的字符串十进制值转换为e表示法,这对于模块文档而言是出乎意料的。

>>> 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. 使用'%f'{:f}字符串格式设置说明,您可以完全控制该值的显示方式。 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__ . 如果要自定义Decimal的默认表示形式,则可以从decimal.Decimal派生一个类,并覆盖.__str__().__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']
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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