我想从小数中删除所有前导零。
例如,0,0000000029应该改为29,或者0,000000710应该改为710。
什么是在python中实现此目的的最简单方法?
很抱歉,如果这是一个明显的问题,但是我还没有找到任何具体的答案,我是一个绝对的初学者。
编辑:我想将其用于我正在编程的Binance加密交易机器人。每种货币都有精度,因此总是给出最大浮点长度。例如,当一种货币的价格为0,00000027时,我希望将其返回为27。
这是使用字符串操作的简单方法:
# Your number, defined to 10 decimal places
x = 0.0000001230
# Convert to string using f-strings with 10 decimal precision
out = f'{x:.10f}'
# Split at the decimal and take the second element from that list
out = out.split('.')[1]
# Strip the zeros from the left side of your split decimal
out = out.lstrip('0')
out
>>> '1230'
作为单线:
out = f'{x:.10f}'.split('.')[1].lstrip('0')
如果要使最终结果为整数或浮点数,只需在使用int(out)
或float(out)
之后将其转换。
编辑:如果要更改精度(必须固定精度以解决尾随零),则只需更改出现在f字符串中的int:out = f'{x:.<precision>f}'
。
您可以使用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的建议使用量化:
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
您也可以使用to_integral(),如此处所示,但我认为以这种方式使用as_tuple更具自记录性。
我在少数情况下对这两种情况进行了测试;如果发现不起作用,请发表评论。
>>> 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')