我有一个python程序,它使用以下正则表达式读取浮点值

 (-?\d+\.\d+)

一旦我使用float(match.group(1))提取值,我得到实际的浮点数。但是,我无法区分数字是1.2345678还是1.234或1.2340000。

我面临的问题是再次打印出浮点值,格式完全相同。一个简单的解决方案是“分裂和计数”。仍为字符串时的浮点值,例如在小数点处分割,并计算整数部分长度和小数部分长度,然后创建格式化为

print "%"+str(total_len)+"."+str(fractional_len)+"f" % value

但也许您知道实现相同结果的标准方法吗?

有帮助吗?

解决方案

你的方法基本上是正确的。 字符串格式有一个较少使用的 * 运算符,您可以为格式化大小,这里是一些代码:

import re

def parse_float(str):
  re_float = re.compile(r'(-?)(\d+)\.(\d+)')
  grps = re_float.search(str)
  sign, decimal, fraction = grps.groups()
  float_val = float('%s%s.%s' % (sign, decimal, fraction))
  total_len = len(grps.group(0))
  print '%*.*f'  % (total_len, len(fraction), float_val)

parse_float('1.2345678')
parse_float('1.234')
parse_float('1.2340000')

并输出

1.2345678
1.234
1.2340000

其他提示

如果要保持固定的精度,请避免使用 float 并使用 Decimal

>>> from decimal import Decimal
>>> d = Decimal('-1.2345')
>>> str(d)
'-1.2345'
>>> float(d)
-1.2344999999999999
>>> from decimal import Decimal as d
>>> d('1.13200000')
Decimal('1.13200000')
>>> print d('1.13200000')
1.13200000
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top