限制浮动以减少数据大小

时间:2016-12-22 03:35:12

标签: python formatting

我使用round()将浮点数限制为n小数点,但我拥有的数据有很多可以减少的值。

例如:

0.0 to 0  
-0.0 to 0  
0.12 to .12  
-0.12 to -.12  
1.0 to 1

如何使用python完成?

3 个答案:

答案 0 :(得分:2)

db.MatchHistory.SqlQuery("SELECT * FROM [dbo].[tblMatchHistory] WHERE id = '" + sumID + "'").ToList().Count()

输出:

x="""0.0 -0.0 0.12 -0.12 1.0 12.0 -12.00 12.001 -12.001 10.01 -10.01 00.12""" def repl(matchobj): return ''.join(i for i in matchobj.groups() if i) print re.sub(r"(-?)(?:\b0+(\.\d)(\d*)(?<!-0\.0)(?<!0\.0)\b|\b([1-9]\d*)\.0+\b)|-?(0)+\.0\b", repl , x)

答案 1 :(得分:1)

因此,您希望在角色级别缩小数字。使用正则表达式:

if n == 0: # Takes care of 0.0, -0.0, 0000.000, etc.
  m = "0"
elif type(n) == int: # Takes care of integer numbers
    m = re.sub(r'^(-)?0+', r'\1', str(n))
elif n > 0: # Takes care of fp positive numbers
    m = re.sub(r'^0+|\.?0+$', '', str(n))
else: # Takes care of fp negative numbers, DIY

答案 2 :(得分:-1)

In [360]: alist=[0.0, -0.0, .12, -.12, 1.0]

Py3样式format中的常规浮点格式:

In [361]: '{}, {}, {}, {}, {}'.format(*alist)
Out[361]: '0.0, -0.0, 0.12, -0.12, 1.0'

n(或g)格式可以到达您想要的位置:

In [362]: '{:n}, {:n}, {:n}, {:n}, {:n}'.format(*alist)
Out[362]: '0, -0, 0.12, -0.12, 1'

它仍然包含0的前导0.12