8.4 Numeric Type Conversion
Converting to int, float, complex, and bool explicitly — why int() truncates toward zero instead of rounding, and how to round first when that's actually what's needed.
The numeric types themselves are covered in 5.3 Numeric Data Types — this section focuses specifically on the rules for converting into each one.
int()
Converts a string of digits, or truncates a float toward zero (discarding the fractional part — it does not round). Also converts bool (True → 1, False → 0).
>>> int("42")
42
>>> int(3.9) # truncates -- NOT rounded
3
>>> int(True)
1
float()
Converts a numeric string or an int to a floating-point value.
>>> float("3.14")
3.14
>>> float(5)
5.0
complex()
Converts a number (or a string in a+bj form) into a complex number with real and imaginary parts.
>>> complex(2)
(2+0j)
>>> complex("3+4j")
(3+4j)
bool()
Converts any value to True or False using Python’s truthy/falsy rules — see 8.8 Boolean Conversion and Type Checking.
>>> bool(0), bool(1), bool(""), bool("x")
(False, True, False, True)
Conversion Rules
int() discards the .99 fractional part — it does not round. Use int(round(3.99)) → 4 if rounding is what’s actually needed.
The most important rule to internalize: int(float_value) always rounds toward zero, never to the nearest whole number. Use round() first if rounding is actually the goal:
>>> int(3.9), int(-3.9) # both truncate toward zero
(3, -3)
>>> int(round(3.9)) # round first, then convert
4
Quick Interview Answer
“
int()parses a digit string or truncates a float toward zero — critically, it does not round, soint(3.9)is3, andint(-3.9)is-3, not-4.float()parses a numeric string or widens anint.complex()builds a complex number from a real number or ana+bjstring.bool()applies the truthy/falsy rules explicitly. When rounding to the nearest whole number is actually the goal,round()first andint()second:int(round(3.9))is4.”
Common Mistakes
- Expecting
int(3.9)to round to4— it truncates toward zero, giving3; useround()first for actual rounding. - Forgetting
int(-3.9)truncates to-3(toward zero), not-4(toward negative infinity, which is what//does) — the two are easy to conflate. - Trying
int("3.14")directly — it raisesValueError, sinceint()expects a string that’s already a whole number; go throughfloat()first (see 8.15 Common Mistakes).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form