-1

What I want is:

if 1700 / 1000 = 1.7 = int(1) # I want this to be True
   lst.append("T")

My original code was:

if 1700 / 1000 == int(1) # This is False and I want it to be True
   lst.append("T")

The if statement is False because the answer is 1.7 and not 1. I would like this to be True. So I want the 1.7 to round down to 1 using int so that the if statement will be True.

rajah9
  • 11,645
  • 5
  • 44
  • 57
Denferno
  • 39
  • 5
  • Welcome to StackOverflow. Some documentation that will help: https://docs.python.org/3.7/library/operator.html#mapping-operators-to-functions . Note that "division" has three flavors. You are looking for the last (which does a floordiv). – rajah9 Jan 08 '21 at 12:09

7 Answers7

5

// always provide integer value. If you want to get always integer then use it otherwise follow int(a/b)

if 1700 // 1000 == int(1):  # I want this to be True
    lst.append("T")
mhhabib
  • 2,975
  • 1
  • 15
  • 29
3

You either need to put the int on the other side:

if int(1700 / 1000) == 1
   lst.append("T")

i.e. round the 1700/1000 to an integer before comparing it, or use //, which is integer division and discards the fraction part:

if 1700 // 1000 == 1
   lst.append("T")
Rup
  • 33,765
  • 9
  • 83
  • 112
3

You can either use the // operator (integer division) or use the floor function from the math module:

>>> from math import floor
>>> floor(1.7/1)
1
>>> floor(1.7/1) == int(1)
True
>>> 1.7 // 1
1.0
>>> 1.7 // 1 == 1
True
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
3

You can try

if int(1700/1000) == 1 # I want this to be True
   lst.append("T")

int(1700/1000) will convert the 1.7 into 1 by ignoring the decimal portion of the number

Aaron Alphonso
  • 336
  • 3
  • 6
1

Everything brilliant is simple

if int(1700 / 1000) == int(1): 
   lst.append("T")
Paitor
  • 251
  • 2
  • 18
1

You should take a look at the floor and ceil functions. The floor function rounds to the last number, whereas ceil to the next. In your case, you need to do it like this:

import math

if math.floor(1700 / 1000) == int(1):
   print("TRUE")
else:
    print("FALSE")

using floor in python

Jacob Celestine
  • 1,758
  • 13
  • 23
0

You could round up or down in Python by 'floor' and 'ceil' methods in the 'math' library.

from math import floor, ceil
print (floor(1.7), ' , ', ceil(1.7))

The result will be

1 , 2

This will work in either Python 2.x or Python 3.x

Amir Maleki
  • 389
  • 1
  • 2
  • 14