python - 从十进制中删除尾随零

标签 python decimal

我有一长串小数,我必须根据特定条件按 10、100、1000、..... 1000000 的因子进行调整。当我将它们相乘时,有时我想去掉一个无用的尾随零(尽管并非总是如此)。比如……

from decimal import Decimal

# outputs 25.0,  PROBLEM!  I would like it to output 25
print Decimal('2.5') * 10

# outputs 2567.8000, PROBLEM!  I would like it to output 2567.8
print Decimal('2.5678') * 1000

是否有一个函数可以告诉十进制对象删除这些无关紧要的零?我能想到的唯一方法是转换为字符串并使用正则表达式替换它们。

可能应该提到我使用的是 python 2.6.5

编辑 senderle 的好回答让我意识到我偶尔会得到一个像 250.0 这样的数字,标准化后会产生 2.5E+2。我想在这些情况下,我可以尝试将它们整理出来并转换为 int

最佳答案

您可以使用 normalize去除额外精度的方法。

>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5

为避免去除小数点左侧的零,您可以这样做:

def normalize_fraction(d):
    normalized = d.normalize()
    sign, digits, exponent = normalized.as_tuple()
    if exponent > 0:
        return decimal.Decimal((sign, digits + (0,) * exponent, 0))
    else:
        return normalized

或者更简洁,使用 user7116 建议的 quantize :

def normalize_fraction(d):
    normalized = d.normalize()
    sign, digit, exponent = normalized.as_tuple()
    return normalized if exponent <= 0 else normalized.quantize(1)

您也可以使用 to_integral(),如图所示 here但我认为以这种方式使用 as_tuple 更能 self 记录。

我在几个案例中对这两种情况进行了测试;如果您发现某些内容不起作用,请发表评论。

>>> normalize_fraction(decimal.Decimal('55.5'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55.500'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55500'))
Decimal('55500')
>>> normalize_fraction(decimal.Decimal('555E2'))
Decimal('55500')

关于python - 从十进制中删除尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227620/

相关文章:

Python 套接字错误 : [Errno 104] Connection reset by peer

python - 将子进程的标准输出/标准错误重定向到文件

r - 设置打印的默认小数位数

python - Numpy 高精度

python - 我如何使用 Youtube api 将整个文件夹上传到 Youtube

python - 如何通过 pyspark/hadoop/etc 提高程序的速度?

python - 从模块调用未定义的方法

python - 在 Python 中仅打印有效数字

java - 十六进制到有符号 32 位转换

c - 在 C 中返回特定数量的小数