2

I have an integer variable which casts into a floating point number as soon as i divide it. I need to stop this from happening

I've tried explicitly casting the variable after declaring it using the int() function but it still converted to a float as soon as i divided it

x = 5
int(x)
x = x/2
type(x)

I expect the output of x/2 since its an integer but the output is 2.5, and when i run it through the type() function it returns a float

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1exip
  • 29
  • 1
  • 3
  • 5
    For integer division, use `x//2` (two slashes instead of one). A single slash produces a floating result (this was a Python 3 change). – Tom Karzes Jun 27 '19 at 23:07

1 Answers1

3

There is no type-casting in Python, there is type conversion.

x = 5
int(x)

This has no impact on variable x as you've created a new (due to small integer ([-5, 256]) interning on CPython, it would be the same object to the original 5 in memory) int object by doing int(x) and throw it away because it has no name referring to it. The original x variable still referring to the integer object 5.

When you divide 5 / 2 the answer is 2.5 which is a float, as shown in the result.

Now, if you want your result as int, you can do:

  • floor division: x // 2 (math.floor(x / 2) would do as well)

  • use round: round(x / 2)

  • ceil division: math.ceil(x / 2) (this would get you 2 hence the name ceiling)

heemayl
  • 39,294
  • 7
  • 70
  • 76