Menu

Casting

int() and float() Conversions

int() and float() are casting functions. Each one takes a value and produces a value of the requested data type: int() gives an integer (a whole number), while float() gives a real number, written with a decimal point.

int() and truncation

Give int() a value that represents a whole number, such as the text "76", and you get that whole number back as an integer. Give it a real number and it truncates: the fractional part is cut off and only the whole number part is kept, so 9.75 becomes 9 and 12.99 becomes 12.

Truncating is not rounding. Rounding would push 12.99 up to 13, but int() simply removes everything after the decimal point, so it does not round up to the next whole number.

float() and real numbers

float() converts a value that represents a number into a real number. Text such as "18.5" becomes the real value 18.5, and an integer is rewritten with a decimal part, so float(45) gives 45.0. The size of the number stays the same; only its data type changes.

Converting between the two types

Starting valueint() of the valuefloat() of the value
"76"7676.0
9.7599.75
313131.0

The direction of the cast decides what happens. Real to integer gives a new integer value without the fractional part, because truncation throws it away. Integer to real keeps the same value and writes it with a decimal part.

race_time = 47.92
whole_seconds = int(race_time)
print(whole_seconds)
print(float(whole_seconds))

Output:

47
47.0

Practise this