Python Code Example: convert specific datatype to int

In Python it is possible to convert data types to other data types. The method int() converts a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal.

Syntax

Here, x can be a number or a string. If x is a number, it can be an integer, a float, or a complex number. If x is a string, it must contain a numeric value, and an optional prefix indicating the base of the number.

int(x)

Example

intNumber = 12
floatNumber = 1.2
numStr = '12'
numChar = '4'

a = intNumber + int(floatNumber)
b = int(numStr) + intNumber
c = int(numChar)

print("data types of a, b and c: " + str(type(a)) 
      + str(type(b)) + str(type(c)))
print("value of a " + str(a))
print("value of b " + str(b))
print("value of c " + str(c))
Output
data types of a, b and c: <class 'int'><class 'int'><class 'int'>
value of a 13
value of b 24
value of c 4