Python如何删除小数? [英] Python how to remove decimal?
问题描述
我找到了其他一些与此相关的主题,但无法使其正常工作。
I've found some other topics on this but I couldn't get it to work. Please pardon my naivety with Python.
Berekening1 = 8.5
Berekening2 = 8.1+4.8
Berekening3 = 8*10
Berekening4 = 3
x = Berekening1 * Berekening2 * Berekening3 + Berekening4
print "Het antwoord van de berekening is:",
round(x); print x,
print "."
我希望 x
为整数。我怎么做?我尝试了 int
和 round
。
I want x
to be an integer. How do I do that? I tried both int
and round
.
也有人对如何删除 x
与之间的空格有所了解。在代码执行结束时结束?
Anyone also have an idea on how to remove the "space" between x
and "." at the end when code is executed?
推荐答案
您需要将x重新分配为 x的值= int(x)
,或者,如果您只想格式化输出,也可以使用str.format:
You would need to reassign x to the value of x = int(x)
or you could also use str.format if you just want the output formatted:
print "Het antwoord van de berekening is: {:.0f}.".format(x)
int和round将表现出不同的行为,如果小数点后有> = 5,则 int
将落下,但是round将四舍五入(如果您想实际使用)回合中,您可能需要将两者结合起来:
int and round will exhibit different behaviour, if you have anything >= 5 after the decimal point then int
will floor but round will round up, if you want to actually use round you might want to combine the two:
In [7]: x = round(1.5)
In [8]: x
Out[8]: 2.0
In [9]: int(x)
Out[9]: 2
或再次与 str.format
组合:
In [10]: print "Het antwoord van de berekening is: {:.0f}".format(round(1.5))
Het antwoord van de berekening is: 2
这篇关于Python如何删除小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!