我希望a四舍五入到13.95.
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
Run Code Online (Sandbox Code Playgroud)
该round功能不像我预期的那样工作.
我一直试图围绕长浮点数,如:
32.268907563;
32.268907563;
31.2396694215;
33.6206896552;
...
Run Code Online (Sandbox Code Playgroud)
到目前为止没有成功.我试过了math.ceil(x),math.floor(x)(虽然那会向上或向下舍入,这不是我正在寻找的)并且round(x)哪些都不起作用(仍然是浮点数).
我能做什么?
编辑:代码:
for i in widthRange:
for j in heightRange:
r, g, b = rgb_im.getpixel((i, j))
h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
h = h * 360
int(round(h))
print(h)
Run Code Online (Sandbox Code Playgroud) 假设我有8.8333333333333339,我想将其转换为8.84.我怎样才能在Python中实现这一目标?
round(8.8333333333333339, 2)给予8.83而不是8.84.我是Python新手或一般编程人员.
我不想将其打印为字符串,结果将进一步使用.有关该问题的更多信息,请查看Tim Wilson的Python编程技巧:贷款和付款计算器.
我如何获得1324343032.324?
如下所示,以下内容不起作用:
>>1324343032.324325235 * 1000 / 1000
1324343032.3243253
>>int(1324343032.324325235 * 1000) / 1000.0
1324343032.3239999
>>round(int(1324343032.324325235 * 1000) / 1000.0,3)
1324343032.3239999
>>str(1324343032.3239999)
'1324343032.32'
Run Code Online (Sandbox Code Playgroud) 我的代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
print (round(1.555, 1)) # It seems normal
print (round(1.555, 2)) # Why it is not output 1.56?
print (round(1.556, 2)) # It seems normal
Run Code Online (Sandbox Code Playgroud)
输出:
sam@sam:~/code/python$ ./t2.py
1.6
1.55
1.56
sam@sam:~/code/python$
Run Code Online (Sandbox Code Playgroud)
round(1.555, 1)输出1.6.
为什么不round(1.555, 2)输出1.56?
Python有默认的round()函数,但是我用cython编程并想用numpy函数替换pythonic代码.但是,在终端中进行实验时,我得到了以下结果.
>>> np.around(1.23456789)
1.0
>>> np.around(1.23456789, decimals=0)
1.0
>>> np.around(1.23456789, decimals=1)
1.2
>>> np.around(1.23456789, decimals=2)
1.23
>>> np.around(1.23456789, decimals=3)
1.2350000000000001
>>> np.around(1.23456789, decimals=4)
1.2345999999999999
Run Code Online (Sandbox Code Playgroud)
这有点奇怪,我仍然想要以下"期望"的结果:
>>> round(1.23456789,3)
1.235
>>> round(1.23456789,4)
1.2346
Run Code Online (Sandbox Code Playgroud) 我使用的是python 2.7,我的代码是:
a = 10.5 * 22.34 / 2.0
print "%.2f" % a
Run Code Online (Sandbox Code Playgroud)
我期望的结果是117.29,但它显示117.28.如何解决问题?
我有一个不断变化的变量,它是一个浮点(例如:2.003)
我想自动将其更改为只有2位小数.