Python:删除除法小数点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17651384/
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: Remove division decimal
提问by Arctoran
I have made a program that divides numbers and then returns the number, But the thing is that when it returns the number it has a decimal like this:
我制作了一个程序,将数字相除,然后返回数字,但问题是当它返回数字时,它有一个像这样的小数:
2.0
But I want it to give me:
但我希望它给我:
2
so is there anyway I can do this?
所以无论如何我可以做到这一点吗?
Thanks in Advance!
提前致谢!
采纳答案by TerryA
You can call int()
on the end result:
您可以调用int()
最终结果:
>>> int(2.0)
2
回答by Inbar Rose
When a number as a decimal it is usually a float
in Python.
当一个数字作为小数时,它通常是float
Python 中的 a。
If you want to remove the decimal and keep it an integer (int
). You can call the int()
method on it like so...
如果要删除小数并保留整数 ( int
)。你可以int()
像这样调用它的方法......
>>> int(2.0)
2
However, int
rounds downso...
然而,int
几轮下来所以......
>>> int(2.9)
2
If you want to round to the nearest integer you can use round
:
如果你想四舍五入到最接近的整数,你可以使用round
:
>>> round(2.9)
3.0
>>> round(2.4)
2.0
And then call int()
on that:
然后调用int()
它:
>>> int(round(2.9))
3
>>> int(round(2.4))
2
回答by Joshwin Vadakkadam
>>> int(2.0)
You will get the answer as 2
你会得到答案为 2
回答by Himanshu
You could probably do like below
你可能会像下面这样
# p and q are the numbers to be divided
if p//q==p/q:
print(p//q)
else:
print(p/q)
回答by delloff
def division(a, b):
return a / b if a % b else a // b
回答by Race
There is a math function modf()
that will break this up as well.
有一个数学函数modf()
也可以分解它。
import math
print("math.modf(3.14159) : ", math.modf(3.14159))
will output a tuple:
math.modf(3.14159) : (0.14159, 3.0)
将输出一个元组:
math.modf(3.14159) : (0.14159, 3.0)
This is useful if you want to keep both the whole part and decimal for reference like:
如果您想同时保留整个部分和小数以供参考,这很有用,例如:
decimal, whole = math.modf(3.14159)
decimal, whole = math.modf(3.14159)