Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Remove division decimal

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!

like image 299
Dan Alexander Avatar asked Jul 15 '13 09:07

Dan Alexander


People also ask

How do you get rid of decimal division?

There cannot be decimals in the divisor; therefore, remove the decimal point from the divisor and add as many zeros to the dividend as there are digits after the decimal point. In this case, we have to add only one zero.

How do you remove the decimal from divisor to make it a whole number?

15 ÷ 0.2 = 75 To divide decimal numbers: Multiply the divisor by as many 10's as we need, until it is a whole number. Remember to multiply the dividend by the same number of 10's.

How do you ignore a float in Python?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places. What is this? The int() function works differently than the round() and floor() function (which you can learn more about here).

How do you find the quotient without a decimal in Python?

In Python 3 Integer division is performed using the // operator, and the regular division operator can yield float. Check 1/2 for example - if you get 0.5 , that's not Integer division, 0 is. IDLE is irrelevant here. If you find an answer elsewhere, please flag as duplicate rather than copying the answer across.


4 Answers

You can call int() on the end result:

>>> int(2.0)
2
like image 124
TerryA Avatar answered Oct 20 '22 13:10

TerryA


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
like image 40
Inbar Rose Avatar answered Oct 20 '22 14:10

Inbar Rose


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)
like image 3
Himanshu Avatar answered Oct 20 '22 15:10

Himanshu


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)

like image 2
raceee Avatar answered Oct 20 '22 15:10

raceee