C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: No rounding actually occurs with int(). Instead it just truncates the value.
Python program that uses int
# Use int to convert floats to integers.
# ... The value is always rounded down (truncated).
value = 1.5
result = int(value)
print(value, "INT =", result)
value = 1.9
result = int(value)
print(value, "INT =", result)
value = -1.9
result = int(value)
print(value, "INT =", result)
Output
1.5 INT = 1
1.9 INT = 1
-1.9 INT = -1
Python program that uses int on string
# Convert a string containing an integer to an int.
data = "123"
result = int(data)
print(data, "INT =", result)
# The result is an integer value.
if result == 123:
print(True)
Output
123 INT = 123
True
Python program that causes int error
# This fails as the string is not in a valid format.
data = "cat"
result = int(data)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 6, in <module>
result = int(data)
ValueError: invalid literal for int() with base 10: 'cat'
Here: We have an array of string literals. Some of them are valid ints like 123 and 0, but some like "cat" and "bird" are not.
Result: We use isdigit to test strings to see if they can be parsed with int. Then we parse only the ones that are valid.
Python program that uses isdigit with int
values = ["123", "cat", "bird", "12.34", "0"]
# Loop over strings.
for v in values:
# See if string is all digits.
if v.isdigit():
# Parse string with int.
result = int(v)
print(v, "INT =", result)
else:
# String will fail parsing.
print(v, "ISDIGIT =", False)
Output
123 INT = 123
cat ISDIGIT = False
bird ISDIGIT = False
12.34 ISDIGIT = False
0 INT = 0