我希望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) 我在这段代码的输出中得到了很多小数(华氏温度到摄氏温度转换器).
我的代码目前看起来像这样:
def main():
printC(formeln(typeHere()))
def typeHere():
global Fahrenheit
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(c):
Celsius = (Fahrenheit - 32.00) * 5.00/9.00
return Celsius
def printC(answer):
answer = str(answer)
print "\nYour Celsius value is " + answer + " C.\n"
main()
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何使程序围绕小数点后两位的每个答案?
任何人都可以解释或提出一个解决方法,为什么当我在Python 3中舍入小数,并将上下文设置为舍入一半时,它将舍入2.5到2,而在Python 2中它正确舍入为3:
Python 3.4.3和3.5.2:
>>> import decimal
>>> context = decimal.getcontext()
>>> context.rounding = decimal.ROUND_HALF_UP
>>> round(decimal.Decimal('2.5'))
2
>>> decimal.Decimal('2.5').__round__()
2
>>> decimal.Decimal('2.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
Decimal('3')
Run Code Online (Sandbox Code Playgroud)
Python 2.7.6:
>>> import decimal
>>> context = decimal.getcontext()
>>> context.rounding = decimal.ROUND_HALF_UP
>>> round(decimal.Decimal('2.5'))
3.0
>>> decimal.Decimal('2.5').quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)
Decimal('3')
Run Code Online (Sandbox Code Playgroud) 我想对一系列数字进行四舍五入,如下所示:
0 -> 0
0.1 -> 0
0.125 -> 0.25
0.25 -> 0.25
Run Code Online (Sandbox Code Playgroud)
我听说我可以使用 round(x*4)/4 来找到最接近的 0.25 单位。但是这个函数在边界处会出现一些问题
0.125 -> 0 (with round(x*4)/4)
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以正确地进行上述舍入吗?谢谢
有人请向我解释为什么会发生这种情况,我似乎找不到正确的答案。舍入整数以获得一致结果的最佳方法是什么?
a = 3.5
b = 2.5
print(f'3.5 rounds up : {round(a)}, 2.5 rounds down: {round(b)}')
Output: 3.5 rounds up : 4, 2.5 rounds down: 2
Run Code Online (Sandbox Code Playgroud)
我预计两个整数都会向下或向上舍入相同。
我想访问内置函数的源代码round(),以允许我创建一个非常相似的函数。我如何访问该源代码以及编辑/使用该源代码的容易程度如何?
round()我对此感兴趣的原因是,即使位数为负,内置函数也会将整数转换为浮点数。例如:
round(1234.5678,-2)
Run Code Online (Sandbox Code Playgroud)
退货
1200.0
Run Code Online (Sandbox Code Playgroud)
我想创建一个返回整数的函数。我确信还有其他方法可以实现相同的结果,但我想看看内置函数如何实现此任务,因为我希望这是相当有效的。