Python如何去除小数点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32669400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python how to remove decimal?
提问by Robo
I've found some other topics on this but I couldn't get it to work. Please pardon my naivety with Python.
我在这方面找到了一些其他主题,但我无法让它发挥作用。请原谅我对 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 "."
I want x
to be an integer. How do I do that? I tried both int
and round
.
我想x
成为一个整数。我怎么做?我尝试了int
和round
。
Anyone also have an idea on how to remove the "space" between x
and "." at the end when code is executed?
任何人也有关于如何删除x
和“。”之间的“空格”的想法。最后什么时候执行代码?
回答by Martijn Pieters
The round()
function cannot alter the x
variable in place, as numbers are immutable. Instead, the rounded result is returned, which your code ignores.
该round()
函数不能x
就地改变变量,因为数字是不可变的。相反,将返回舍入结果,您的代码将忽略该结果。
Store the result back in x
:
将结果存储回x
:
x = round(x)
This will give you a floating point number rounded to the nearest whole number.
这将为您提供一个四舍五入到最接近的整数的浮点数。
Alternatively, use x = int(x)
, which gives you an integer number, but floorsthat number (removes the decimal portion regardless if it is closer to the next whole number or not).
可替代地,使用x = int(x)
,它给你的整数,但地板该号码(无论去除小数部分,如果它更接近下一个整数或没有)。
回答by Padraic Cunningham
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:
您需要将 x 重新分配给的值,x = int(x)
或者如果您只想格式化输出,也可以使用 str.format :
print "Het antwoord van de berekening is: {:.0f}.".format(x)
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:
int 和 round 将表现出不同的行为,如果小数点后有 >= 5 的任何内容,int
则将向下取整,但 round 将向上取整,如果您想实际使用 round,您可能希望将两者结合起来:
In [7]: x = round(1.5)
In [8]: x
Out[8]: 2.0
In [9]: int(x)
Out[9]: 2
Or again combine with str.format
:
或者再次结合str.format
:
In [10]: print "Het antwoord van de berekening is: {:.0f}".format(round(1.5))
Het antwoord van de berekening is: 2
回答by aryaman
For just removing decimal part of an integer(eg- 45.55 to 45), you can try using trunc()
method with math library, just like this-
对于仅删除整数的小数部分(例如- 45.55 到 45),您可以尝试使用trunc()
带有数学库的方法,就像这样-
import math
i=45.55
i=math.trunc(i)
print(i)
Output will be- 45, trunc() method doesn't rounds off the integer to the nearest whole number, it justs cuts off the decimal portion.
输出将是- 45,trunc() 方法不会将整数四舍五入到最接近的整数,它只是截断小数部分。
Or if you want to round off then you can use the round()
method.
或者,如果您想四舍五入,则可以使用该round()
方法。