Concepts / Converting to Integers with int()

Converting to Integers with int()

float() converts integers and numeric strings to floating-point numbers, adding decimal representation where none existed.

  • Programming
Interactive lab

Try it: Type conversion: int(), float(), str(), bool()

Exactly how int(), int(text, base), float(), str() and bool() turn a value into another type: Python's real parsing rules for text (whitespace, sign, underscores, 0x/0o/0b prefixes, inf/nan, exponents) and its truthiness rules.

How it works

  1. int(text) strips surrounding whitespace, allows one sign, then reads digits (underscores only between digits); any other character raises ValueError: invalid literal for int().
  2. int(text, base) reads digits in that base; base 0 takes the base from a 0x / 0o / 0b prefix like a Python literal.
  3. float(text) accepts decimals like '.5', '5.', '1e3' and the names inf, infinity and nan, then rounds to the nearest double.
  4. int() of a float truncates toward zero; str() gives the printed form (repr digits for floats).
  5. bool() is truthiness: '', 0, 0.0 and None are False; every non-empty string — even '0' or 'False' — is True.

Default run (8 steps): int(' -0x_1F ', 0): the argument is a str of 10 characters. … int(' -0x_1F ', 0) → -31

Simplified: The argument is a Python literal typed as text (ASCII only; escapes \t \n \r). Unicode digits and bytes arguments are not modelled.

Educational simulation

Loading the simulation…

A Decimal Does Not Round Itself

Suppose a calculation produces 3.9, but the next step requires an integer. Passing the value to int() does not ask Python to choose the nearest whole number. Instead, int() removes the decimal portion. The result is 3. This same rule applies to larger decimal portions: 3.99999 becomes 3, not 4.

What do you think happens?

What values will int() produce for 3.9, -3.9, and 7.0?

  • 4, -4, and 7

  • 3, -3, and 7

  • 3.9, -3.9, and 7.0

Reveal answer
Answer:

3, -3, and 7

int() truncates by removing the decimal portion. It does not round to the nearest integer, so 3.9 becomes 3 and -3.9 becomes -3.

What int() Changes

int() converts values to integers by truncating their decimal portions. For a floating-point input, the digits after the decimal point are removed entirely. The size of the removed portion does not change the rule: both 3.1 and 3.99999 become 3. A whole-number floating-point value such as 7.0 becomes the integer 7.

python
Output (expected)
3
-3
7
3
3.9floating-point value3integer-3.9floating-point value-3integer7.0floating-point value7integerint()int()int()
What changes when int() receives positive, negative, and whole-number floating-point values?

Which Inputs Are Accepted

The source identifies two important input categories for int(). Floating-point values can be converted, and strings that represent whole numbers can be converted. A string containing a decimal representation, such as '3.14', cannot be passed directly to int(); that input raises an error. Invalid input also raises an error.

Input valueSupported forminteger, float, orwhole-number stringIntegeralready an integerInteger resultFloating-point valuedecimal portion istruncatedErrorWhole-number stringdigits represent an integerDecimal stringfor example, '3.14'Invalid inputdoes not represent a validnumberinspect inputintegerfloatwhole-number stringdecimal stringinvalid formconverttruncateconvertraiseraise
How does int() decide whether an input can become an integer or should raise an error?
python
Output (expected)
12
12
12
raises an error
Worked example

Converting a Decimal String

You receive the string '3.14' and need an integer.

  1. 1
    Direct conversion

    int('3.14') raises an error because the string represents a decimal number rather than a whole number.

  2. 2
    Convert to floating point

    float('3.14') converts the numeric string to a floating-point value.

  3. 3
    Convert to integer

    int(float('3.14')) then truncates the decimal portion.

Result

int(float('3.14')) produces 3.

int(), float(), and str()

These conversion functions do different jobs. int() produces an integer and removes a decimal portion when the input has one. float() produces a floating-point value and preserves fractional values. The source also distinguishes both numeric conversions from str(), which is a separate conversion choice rather than an operation that applies int()'s truncation rule.

3.9original valueint()integer result: 3float()floating-point result: 3.9str()string representationtruncatepreserve fractionconvert separately
How does the same decimal value differ when passed through int(), float(), or str()?
FunctionResult described in the sourceEffect on 3.9
int()Integer; decimal portion is truncated3
float()Floating-point value; fractional value is preserved3.9
str()A separate conversion choice from numeric conversionUse when a string representation is required

Choose the function according to the kind of result needed.

Mistakes Beginners Make

  • Common mistake

    Expecting int() to round to the nearest integer.

    What it looks like
    int(3.9) is expected to be 4.
    Why it fails

    int() truncates by removing the decimal portion; it does not round.

    Do this instead
    Expect int(3.9) to produce 3.
  • Common mistake

    Assuming the size of the decimal portion changes the result.

    What it looks like
    int(3.99999) is expected to be 4 because the value is close to 4.
    Why it fails

    The truncation rule removes the decimal portion regardless of its magnitude.

    Do this instead
    Expect int(3.99999) to produce 3.
  • Common mistake

    Passing a decimal string directly to int().

    What it looks like
    int('3.14')
    Why it fails

    int() works with whole-number strings, but a decimal string raises an error.

    Do this instead

    Use int(float('3.14')) when the intended process is to convert the decimal string and then truncate it.

  • Common mistake

    Using float() when an integer result is required.

    What it looks like
    float('12')
    Why it fails

    float() returns a floating-point value rather than an integer.

    Do this instead

    Use int('12') when the input is a whole-number string and an integer result is required.

Check Your Prediction

MEDIUM

Predict the result of each expression before checking it: int(8.75), int(-8.75), int('8'), int('8.75'), and int(float('8.75')). For each one, decide whether the result is an integer or an error, and explain what happened to the decimal portion.

Hints
  • For a floating-point input, int() removes the decimal portion.
  • A string containing only a whole number can be converted directly.
  • A decimal string needs float() before int() if truncation is intended.

Key Takeaways

  1. 1
    int() converts supported values to integers.
  2. 2
    For floating-point inputs, int() truncates by removing the decimal portion rather than rounding.
  3. 3
    int() can convert floats and whole-number strings, but decimal strings and invalid input raise an error.
  4. 4
    To convert a decimal string to an integer through truncation, use int(float('3.14')).
  5. 5
    float() preserves fractional values in a floating-point result, while str() represents a separate conversion choice.

At a glance

  • int() removes decimal portions; it does not round.
  • Values such as 3.9, -3.9, and 7.0 become 3, -3, and 7.
  • Floating-point values and whole-number strings can be converted with int().
  • Decimal strings cannot be passed directly to int(); convert them with float() first when truncation is wanted.
  • float() preserves fractions, so it behaves differently from int().

More concepts starting with C