PythonPython Variables and Data TypesPython data types

What is the difference between integers and floating-point numbers?

Question 33 of 88 · Updated

On this page

An integer (int) represents an exact whole number, while a floating-point number (float) represents a real-valued quantity using a finite-precision numerical representation. Python integers have arbitrary precision, limited by available resources. Python floats typically use IEEE 754 double-precision binary floating point, which supports fractional values and a wide magnitude range but cannot represent every real number exactly.

Use integers for exact counts, indexes and whole-number arithmetic. Use floats for measurements, scientific calculations and other quantities where approximation is acceptable. The choice affects arithmetic results, rounding, numerical stability and the correctness of applications.

1. Integer vs floating-point number: comparison#

Propertyintfloat
Examples42, -7, 03.14, -7.0, 1e3
RepresentsWhole numbersFinite-precision real-valued quantities, plus special values
PrecisionExact integer values, subject to resourcesLimited significant binary digits
RangeArbitrarily large magnitudes subject to resourcesFinite range for finite values
MutabilityImmutableImmutable
Typical usesCounts, IDs, indexes, exact discrete arithmeticMeasurements, averages, simulations
Special valuesNo infinity or NaNInfinity, negative infinity and NaN
Bitwise operationsSupported for integersNot supported for ordinary floats

Python does not enforce a permanent type on ordinary variable names. The type belongs to the object.

PYTHON
print(type(7).__name__, type(7.0).__name__, type(1e3).__name__)

Output:

int float float

Although 7 and 7.0 represent equal numerical quantities, they are objects of different types. Scientific notation such as 1e3 creates a float, even when its numerical value is a whole number.

2. How Python integers represent exact values#

Python 3 has one built-in integer type. Its precision is not restricted to a signed 32-bit or 64-bit machine word.

PYTHON
print(2**100)

Output:

1267650600228229401496703205376

The result is an exact integer. In CPython, large integers are represented internally using multiple digits in an implementation-specific base. The interpreter allocates additional storage as necessary.

Arbitrary precision does not mean infinite memory or constant-time arithmetic. The time and space required by large integer calculations depend on the magnitude of the operands and the algorithm used. Operations can fail when implementation limits or available resources are exceeded. Certain integer-to-string conversions can also have configured safety limits.

This makes int particularly useful for counters, exact identifiers, combinatorics and discrete arithmetic. Do not convert a large identifier to float merely to store it as a number.

3. How floating-point numbers represent values#

On most modern CPython platforms, float corresponds to the IEEE 754 binary64 format. A finite normal binary64 value uses a sign, an exponent and a significand. Conceptually its magnitude is a binary fraction scaled by a power of two.

The usual binary64 format has 53 bits of significand precision (including the implicit leading bit for normal values), which corresponds to roughly 15–17 significant decimal digits, depending on what conversion or round-trip guarantee is being discussed. Subnormal values behave differently near zero.

A float is not a fixed number of decimal places. Precision is relative to magnitude: the distance between adjacent representable values generally grows as magnitude increases.

Check the actual runtime rather than assuming its representation:

PYTHON
import sys print(sys.float_info.radix, sys.float_info.mant_dig, sys.float_info.max_exp)

Output on the tested CPython 3.13.5 environment:

2 53 1024

The radix is 2, significand precision is 53 binary digits, and the maximum exponent field reported by sys.float_info is expressed using the C floating-point conventions. These values are consistent with binary64. They are not a guarantee about every Python implementation or platform.

4. Why converting a large integer to float can lose information#

On the tested binary64 platform, every integer from negative 253 through positive 253 is exactly representable as a float. Beyond that boundary, some integers cannot be represented exactly.

PYTHON
print(2**53 + 1, int(float(2**53 + 1)), float(2**53) == float(2**53 + 1))

Output:

9007199254740993 9007199254740992 True

The original integer is exact. Conversion to float rounds it to a representable value. Converting that float back to an integer cannot recover the lost information.

Loading diagram…

This diagram illustrates the observed rounding behaviour on binary64. It shows why converting identifiers, large counters or exact integer quantities to float can collapse distinct values.

Some larger integers, such as 2**54, are still exactly representable; the limitation concerns the spacing between representable values, not a hard maximum exact integer magnitude.

The math module can inspect this spacing:

PYTHON
import math print(math.ulp(1.0), math.ulp(float(2**53)), math.nextafter(float(2**53), math.inf))

Output:

2.220446049250313e-16 2.0 9007199254740994.0

At 2**53 the next larger binary64 float is two units away. The intervening integer cannot be represented. math.ulp reports a unit in the last place, while math.nextafter moves toward another representable value.

5. Why 0.1 + 0.2 is not exactly 0.3#

Many decimal fractions cannot be represented by a finite binary fraction. For example, decimal 0.1 has a repeating binary expansion.

PYTHON
import math print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))

Output:

0.30000000000000004 False True

Python stores nearby representable values for the decimal literals and performs floating-point arithmetic on them. The resulting sum is close to the intended decimal value, but it is not equal to the float produced by the literal 0.3.

To inspect the exact rational value of the stored float:

PYTHON
print((0.1).as_integer_ratio()) print((0.1).hex())

Output:

(3602879701896397, 36028797018963968)
0x1.999999999999ap-4

The first result is the numerator and denominator of the actual stored value, not the fraction 1/10. The hexadecimal representation is useful when exact binary floating-point inspection is needed.

This behaviour follows from finite-precision binary representation, not a defect specific to Python.

6. Arithmetic: division, floor division and remainder#

Python 3 distinguishes true division from floor division.

PYTHON
print(7 / 2, 7 // 2, -7 // 2, -7 % 2) print(7 // 2.0, type(7 // 2.0).__name__)

Output:

3.5 3 -4 1
3.0 float
ExpressionExplanation
7 / 2True division returns a float for these int operands
7 // 2Floor division returns the integer 3
-7 // 2Floors toward negative infinity, giving -4
-7 % 2Integer remainder 1, consistent with the floor quotient
7 // 2.0Mixed floor division returns a float, 3.0

Do not confuse floor division with truncation toward zero. With negative numbers, the results differ.

The quotient and remainder identity holds exactly for integer operands with a nonzero divisor: a = (a // b) * b + (a % b). Floating-point arithmetic has additional rounding limitations.

Even true division of two integers can require a floating-point result and can overflow if that result cannot be represented.

7. Mixed integer and float operations#

When ordinary integer and floating-point operands participate in supported arithmetic operations such as addition, the integer is converted to the floating-point representation needed for the operation.

PYTHON
print(2 + 0.5, type(2 + 0.5).__name__) print(1 == 1.0, len({1, 1.0}))

Output:

2.5 float
True 1

Python's numeric equality can compare an integer and float as equal even though their types differ. Equal numeric values also have equal hashes, so 1 and 1.0 represent one distinct element in the set example.

Do not infer that mixed comparisons always convert both operands to floats. Python's comparison semantics account for numerical value, including cases where simply rounding an integer to a float would give an incorrect equality result.

An operation such as 2 + '0.5' is not valid numeric addition because a string is not automatically parsed as a number.

8. Converting float to int: truncation, floor, ceiling and round#

Different operations express different mathematical intentions.

PYTHON
import math print(int(-3.9), math.floor(-3.9), math.ceil(-3.9), round(2.5), round(3.5))

Output:

-3 -4 -3 2 4
OperationMeaning
int(x) for finite float xTruncates toward zero
math.floor(x)Largest integer no greater than x
math.ceil(x)Smallest integer no less than x
round(x) with no ndigitsNearest integer, with ties going to the even choice for ordinary floats

Rounding of decimal-looking floats can surprise users because the actual stored value may differ from the decimal literal. For exact decimal rounding policies, use Decimal created from decimal strings or an appropriate integer representation.

The integer constructor does not check whether discarding a fractional part is acceptable for your application. Validate input before converting if loss of the fraction would be an error.

9. Comparing floating-point results safely#

For approximate calculations, math.isclose can compare two values using relative and absolute tolerances.

PYTHON
import math print(math.isclose(1e-12, 0.0), math.isclose(1e-12, 0.0, abs_tol=1e-9))

Output:

False True

Relative tolerance alone is not generally sufficient when comparing a small nonzero value with zero. A meaningful absolute tolerance can address this case.

For finite numbers, math.isclose uses a criterion based on the larger of the relative tolerance scaled to the larger absolute operand and the specified absolute tolerance. The default relative tolerance is 1e-9 and the default absolute tolerance is zero.

Choose tolerances according to the problem's units, expected error and accuracy requirements. A tolerance that is suitable for comparing physical measurements might be unacceptable for billing or security-sensitive threshold decisions.

Approximate equality is not a substitute for exact equality of integers, identifiers or other discrete values. It also need not be transitive, so it should not be used casually as an equivalence relation for grouping keys.

10. Infinity, NaN, signed zero and overflow#

Floating-point values can represent special cases such as infinity and NaN (not a number).

PYTHON
import math print(math.isfinite(float('inf')), math.isnan(float('nan')), float('nan') == float('nan'), -0.0 == 0.0)

Output:

False True False True

NaN is not equal to itself under ordinary floating-point equality. Test for it using math.isnan. Use math.isfinite when an input must be neither infinite nor NaN.

Positive and negative floating-point zero compare equal, but the sign can be observed in some operations, for example through math.copysign.

Python float arithmetic does not always behave as a raw hardware operation. Ordinary Python division by zero raises ZeroDivisionError even when the operands are floats. Conversion of an extremely large integer to float may raise OverflowError. Converting infinity to int raises OverflowError; converting NaN to int raises ValueError.

The four error cases below were individually tested:

PYTHON
float(10**400) # OverflowError on tested binary64 runtime int(float('inf')) # OverflowError int(float('nan')) # ValueError 1.0 / 0.0 # ZeroDivisionError

Run these expressions separately or handle their exceptions; the first uncaught exception stops a sequential script.

11. Exact decimal and rational arithmetic#

When the application needs semantics that differ from binary floating point, Python's standard library provides alternatives.

PYTHON
from decimal import Decimal from fractions import Fraction print(Decimal('0.1') + Decimal('0.2')) print(Fraction(1, 3) + Fraction(1, 6))

Output:

0.3
1/2

Decimal represents decimal quantities with arithmetic controlled by a context, including precision and rounding. Constructing Decimal from a string preserves the intended decimal input; constructing it from a float instead captures the float's existing binary approximation exactly.

Fraction represents rational numbers as integer numerators and denominators. It is useful when exact rational arithmetic is important, but numerator and denominator sizes may grow substantially.

Neither is a universal replacement for float. Decimal operations can round according to their context, and rational arithmetic can require substantially more time and memory than ordinary machine floating-point arithmetic.

12. Practical example: money and physical measurements#

Suppose an application charges a fixed price of 19.99 for three items. A suitable decimal calculation with an explicitly chosen rounding policy is:

PYTHON
from decimal import Decimal, ROUND_HALF_UP print((Decimal('19.99') * 3).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))

Output:

59.97

This example assumes a currency with two decimal places and a particular rounding policy. Real financial systems must use the applicable currency, tax, accounting and contractual rounding rules. Integer minor units are also an appropriate representation for many exact monetary workflows.

For measurements or simulations where binary approximations are acceptable, float is often a practical default. For summing floating-point data, math.fsum can reduce error from cancellation and accumulation compared with naive sequential addition.

PYTHON
import math print(sum([1e16, 1.0, -1e16]), math.fsum([1e16, 1.0, -1e16]))

Output on Python 3.13.5:

1.0 1.0

Modern Python versions have improved float summation algorithms in sum. Older versions or different implementations may produce different results for ordinary sum. The example therefore does not establish that sum is always inaccurate or that fsum is always necessary.

13. Performance and type selection#

A Python int operation on an arbitrarily large integer is not constant-time simply because it uses an arithmetic operator. Addition generally scales with the number of internal digits, and multiplication costs depend on operand sizes and the implementation's algorithm.

Floating-point values have bounded representation size on ordinary binary64 platforms. Basic arithmetic can use machine floating-point facilities, but Python object overhead, special cases and algorithmic structure still matter.

For n values of bounded size, a simple linear summation performs O(n) arithmetic operations. This does not imply O(n) bit complexity for arbitrarily large integers or that every numerical implementation has the same memory footprint.

Choose the numerical representation based on correctness first. Benchmark realistic workloads if performance is material.

14. Common mistakes and best practices#

MistakeBetter approach
Storing a large exact ID as a floatPreserve the integer or a suitable string representation
Expecting 0.1 + 0.2 == 0.3Use an appropriate tolerance for approximate calculations
Using int to round to the nearest integerSelect round, floor, ceil or truncation intentionally
Using float for exact decimal money without a policyUse reviewed Decimal or integer minor-unit arithmetic
Assuming int has a fixed 64-bit limitUnderstand arbitrary precision and resource constraints
Accepting NaN or infinity as ordinary finite inputsValidate using math.isfinite
Assuming // truncates negative valuesRemember floor division rounds toward negative infinity

Frequently asked questions#

Is 5.0 an integer in Python?#

It is a float object with a whole-number value. Its type remains float.

Can an integer be too large for a float?#

Yes. Conversion may round away integer precision or raise OverflowError for values outside the representable range.

Are floats always inaccurate?#

No. Values such as 0.5 are exactly representable in binary floating point. Other values, including 0.1, require approximation. Arithmetic can also introduce rounding.

Why does Python return a float for 4 / 2?#

Python 3 true division of ordinary integer operands returns a floating-point result, even when the quotient is a whole number.

Should every calculation use Decimal?#

No. Decimal is useful where decimal semantics and rounding are required. Float is suitable for many scientific and approximate calculations, and int is appropriate for exact whole numbers.

Interview-ready answer#

Python's int type represents exact whole numbers with arbitrary precision, limited by available resources. The float type represents real-valued quantities using finite-precision floating point, typically IEEE 754 binary64. Floats can represent fractional values and special values such as infinity and NaN, but many decimal fractions and large integers cannot be represented exactly. Integer arithmetic is preferable for exact counts and discrete values, while floats suit approximate numerical calculations. Python 3 uses / for true division and // for floor division. Use suitable tolerance comparisons for approximate results and Decimal or integer minor units when exact decimal arithmetic and rounding policies are required.

Official references#

Verification note: Local CPython 3.13.5 execution confirmed the numerical outputs, binary64 parameters, exact integer arithmetic, conversion precision loss, division, rounding, special values, tolerance comparisons, decimal and rational arithmetic and all four expected exception types. The Mermaid flowchart was manually reviewed for syntax and conceptual accuracy; a local Mermaid parser was unavailable. Official reference links are supplied under the authorised offline research exception, and live references and website rendering were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design