Python: Remove division decimal

若如初见. 提交于 2019-11-29 05:21:13

问题


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!


回答1:


You can call int() on the end result:

>>> int(2.0)
2



回答2:


When a number as a decimal it is usually a float in Python.

If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

>>> int(2.0)
2

However, int rounds down so...

>>> int(2.9)
2

If you want to round to the nearest integer you can use round:

>>> round(2.9)
3.0
>>> round(2.4)
2.0

And then call int() on that:

>>> int(round(2.9))
3
>>> int(round(2.4))
2



回答3:


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)



回答4:


def division(a, b):
    return a / b if a % b else a // b



回答5:


>>> int(2.0)

You will get the answer as 2




回答6:


There is a math function modf() that will break this up as well.

import math

print("math.modf(3.14159) : ", math.modf(3.14159))

will output a tuple: 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)



来源:https://stackoverflow.com/questions/17651384/python-remove-division-decimal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!