Python: Remove division decimal

175,961

Solution 1

You can call int() on the end result:

>>> int(2.0)
2

Solution 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

Solution 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)

Solution 4

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)

Solution 5

>>> int(2.0)

You will get the answer as 2

Share:
175,961
Dan Alexander
Author by

Dan Alexander

Updated on June 02, 2020

Comments

  • Dan Alexander
    Dan Alexander almost 4 years

    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!

  • Inbar Rose
    Inbar Rose almost 11 years
    If this helped you, you could Accept my Answer
  • Jeff
    Jeff about 10 years
    What if it is a large number?
  • Inbar Rose
    Inbar Rose about 10 years
    @Jeff Why don't you check yourself? Python does not have a problem with the size of numbers.
  • Jeff
    Jeff about 10 years
    Thanks! I realized that a bit after I posted. For whatever reason, I thought that a unix date format would be too large a number, but I was wrong!
  • Liza
    Liza almost 9 years
    ValueError: invalid literal for int() with base 10: '68.0'
  • TerryA
    TerryA almost 9 years
    @Kyrie You can do int(float('68.0'))
  • Mark Dickinson
    Mark Dickinson over 8 years
    What does this add that isn't already present in the other answers?
  • Bear
    Bear over 7 years
    @TerryA It won't work in case of int(1.9999999999999999999), how can I just remove the decimals?
  • hobbes3
    hobbes3 about 5 years
    @Bear math.floor(1.9999999999999999999)
  • stackdaemon
    stackdaemon over 4 years
    Thank you, this helped me solve a different but related issue. :)
  • Jerzy
    Jerzy almost 4 years
    @jayveesea Thanks for the tip, I'm still new on the site and in programming overall.