从十进制删除尾随零 [英] drop trailing zeros from decimal

查看:89
本文介绍了从十进制删除尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一长串的十进制数,我必须根据某些条件将其调整为10、100、1000,.... 1000000。当我将它们相乘时,有时会想要删除一个无用的尾随零(尽管并非总是如此)。例如...

I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes a useless trailing zero (though not always) that I want to get rid of. For example...

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

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

Is there a function that tells the decimal object to drop these insignificant zeros? The only way I can think of doing this is to convert to a string and replace them using regular expressions.

应该提到我正在使用python 2.6.5

Should probably mention that I am using python 2.6.5

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

EDIT senderle's fine answer made me realize that I occasionally get a number like 250.0 which when normalized produces 2.5E+2. I guess in these cases I could try to sort them out and convert to a int

推荐答案

可能有更好的方法,但您可以使用 .rstrip('0')。rstrip('。')来获得所需的结果。

There's probably a better way of doing this, but you could use .rstrip('0').rstrip('.') to achieve the result that you want.

以您的数字为例:

>>> s = str(Decimal('2.5') * 10)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
25
>>> s = str(Decimal('2.5678') * 1000)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
2567.8

这是杰里特在评论中指出的问题的解决方法:

And here's the fix for the problem that gerrit pointed out in the comments:

>>> s = str(Decimal('1500'))
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
1500

这篇关于从十进制删除尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆