Does Python Have Doubles? Understanding Float

When a Python calculation needs a particular kind of numeric representation, it helps to know what the built-in float provides. On standard builds, float uses double-precision binary floating point, while Decimal and Fraction offer other ways to represent values.

This article explains how those types differ and how to choose one for your calculation.

TL;DR

Python’s built-in float is normally a 64-bit double-precision binary floating-point value, so a separate built-in double type is not needed.

  • Use float for general scientific and numerical calculations.
  • Use Decimal from text when decimal arithmetic and controlled rounding matter.
  • Use Fraction when an exact rational value is useful.

What Is a Python Double?

On standard Python builds, float uses IEEE 754 binary64, commonly called double precision, with 53 significant binary bits that hold about 15 to 17 decimal digits.

I ran python3 float_demo.py and saw 0.30000000000000004, followed by False when the result was compared with 0.3:

15
0.30000000000000004
False
Python float output with 0.30000000000000004 and a false equality check
The terminal displays a sum and its equality comparison.

The Python floating-point tutorial explains how binary representation affects arithmetic.

For approximate results, math.isclose() compares a relative difference against an absolute floor. Its default abs_tol is zero, so near-zero comparisons need an explicit positive value.

How to Choose and Use Python Numeric Types

Choose a type based on the calculation’s rounding and representation requirements.

Step 1: Read input and inspect float limits

The built-in float() converts numeric text into a binary floating-point value. I ran python3 float_basics_demo.py to check the parsed type, its range and the spacing between nearby values.

import math
import sys

value = float("12.75")
print(value)
print(type(value).__name__)
print(sys.float_info.dig)
print(0.1 + 0.2)
print((0.1 + 0.2) == 0.3)
print(sys.float_info.max)
print(sys.float_info.epsilon)
print(math.ulp(1.0))
print(math.ulp(1e16))
print(1e16 + 1.0 == 1e16)
print(10**16 + 1)
print(float(10**16 + 1))

The output is:

12.75
float
15
0.30000000000000004
False
1.7976931348623157e+308
2.220446049250313e-16
2.220446049250313e-16
2.0
True
10000000000000001
1e+16
Python float output showing spacing and a large integer rounded during conversion
Float spacing and integer conversion output.

The output begins with the parsed number and the float type name. sys.float_info.max is the largest finite float, while epsilon describes spacing near one.

math.ulp(1.0) measures spacing near one, while math.ulp(1016) is 2.0. At that magnitude, adjacent representable floats are two units apart.

Python int preserves 10000000000000001, while converting it to float yields 1e+16, so use int for counters whose steps must stay distinct. float() accepts scientific notation. Catch ValueError for malformed text and validate domain bounds after parsing.

Step 2: Use Decimal for decimal arithmetic

Construct Decimal from text when the written decimal digits define the input value.

from decimal import Decimal, localcontext

print(Decimal('0.1') + Decimal('0.2'))
with localcontext() as context:
    context.prec = 8
    print(Decimal(1) / Decimal(7))
print(Decimal(0.1))
0.3
0.14285714
0.1000000000000000055511151231257827021181583404541015625
Decimal addition, context-limited division and float conversion output
Output shows Decimal addition, division at eight digits and float conversion.

The first line adds decimal tenths. The division uses eight significant digits, while the final line prints the Decimal created from a float.

quantize() sets a fixed exponent such as cents. Decimal defaults to ROUND_HALF_EVEN, so set another mode when a contract specifies it.

localcontext() scopes a precision change to one block, so reusable code can avoid changing settings for unrelated Decimal calculations. Construct decimals from text when the entered digits matter. Decimal(‘1.20’) compares numerically equal to Decimal(‘1.2’) but retains a different exponent, so keep the original text separately when input scale is a requirement.

Step 3: Use Fraction for exact ratios

fractions.Fraction accepts integer numerators, decimal text or float inputs. I ran python3 fraction_demo.py to compare the resulting forms.

from fractions import Fraction

print(Fraction(1, 10) + Fraction(2, 10))
print(Fraction(0.1))
print(Fraction('0.1'))
print(Fraction(0.1).limit_denominator(10))
3/10
3602879701896397/36028797018963968
1/10
1/10
Fraction outputs from float and text inputs, including bounded approximation
Fraction output includes a bounded approximation of a float.

The first line adds two tenths. The second prints a long fraction from float input, while the third and fourth lines both show 1/10 from text or a denominator bound.

Repeated rational operations can enlarge numerators and denominators, increasing memory use and calculation time, a trade-off that matters in long loops even when results are exact.

A reduced denominator containing a prime factor other than two or five yields a repeating decimal expansion. When a float is known to approximate a simple ratio, limit_denominator() can find a nearby Fraction under a chosen bound. Set that bound from the domain because it cannot recover the original input text.

Step 4: Use NumPy dtypes for arrays

I ran python3 numpy_precision_demo.py to check NumPy’s dtype and value output for arrays.

import numpy as np

info = np.finfo(np.longdouble)
print(np.dtype(np.longdouble))
print(np.finfo(np.float64).nmant)
print(info.nmant)
print(info.maxexp)

values_from_float = np.array([0.1, 0.2], dtype=np.longdouble)
values_from_text = np.array(["0.1", "0.2"], dtype=np.longdouble)
print(np.format_float_scientific(values_from_float[0], unique=False, precision=35))
print(np.format_float_scientific(values_from_text[0], unique=False, precision=35))
print(np.format_float_scientific(values_from_text.sum(), unique=False, precision=35))
float128
52
112
16384
1.00000000000000005551115123125782702e-01
1.00000000000000000000000000000000005e-01
3.00000000000000000000000000000000039e-01
NumPy longdouble metadata and array values from float and text inputs
The output compares longdouble metadata and values from float and text arrays.

NumPy reports float128 for longdouble with 112 mantissa bits and maxexp 16384, compared with 52 bits for float64. Inspect finfo on each target because other platforms may use another format.

The first scientific-notation line starts from Python float literals. The second converts decimal text directly to longdouble, and its sum still has a small binary rounding remainder.

A dtype conversion can overflow when the target range is narrower and can round away fractional detail. Check boundary values before writing converted arrays or passing them to another package.

Step 5: Round a float with round()

Python’s round() returns a number at the requested decimal scale. A format specifier creates display text instead of changing the value used by later arithmetic. Without ndigits, round() returns an integer.

for value in (2.675, 2.685):
    print(round(value, 2))

print(round(2.5), round(3.5))
print(round(146, -1), round(144, -1))
2.67
2.69
2 4
150 140
Python round() output for decimal-looking floats, ties and tens rounding
The output shows decimal rounding, ties to even and rounding to tens.

The first result is 2.67 because the stored value for 2.675 lies below the halfway point. Exact integer ties round to the even result, as the final pair shows.

A negative ndigits rounds to tens or hundreds, while positive values keep places after the decimal point. For financial totals, apply the required rounding rule at the reporting boundary instead of rounding every intermediate value.

Step 6: Sum a list of floats with math.fsum()

I ran python3 summation_demo.py with small terms mixed among large values to compare math.fsum() with sum().

import math

values = [1.0, 1e16, 0.1, 1e-5, -1e16]
print(sum(values))
print(math.fsum(values))
1.1000100000000002
1.10001
Python sum and math.fsum totals for mixed-magnitude float values
Mixed-magnitude inputs and their two displayed totals.

The large pair cancels, leaving small terms that can be lost during intermediate rounding. The totals differ in the last digits, and math.fsum() is closer for this input.

Python 3.14.7 uses the float sum() algorithm introduced in Python 3.12, so include the interpreter version when reproducing these results.

When Higher Precision Is Needed

Higher precision helps when rounding error from binary64 changes a decision or accumulates across a calculation. It does not repair uncertain measurements, a poor algorithm or values that were already rounded before they reached Python.

Identify the source of the error first. Preserve decimal measurements as text for decimal arithmetic, and keep ratios and counts exact until conversion is required.

Evaluate a binary-precision library when a numerical algorithm needs extra digits.

Comparison tolerances should come from the scale and meaning of the quantity. math.isclose() accepts relative and absolute tolerances, and its zero default for abs_tol means a comparison near zero needs an explicit floor. A tolerance that is too loose can hide a meaningful difference, while one that is too tight can reject results that differ only through expected rounding.

More digits also cost memory or time in some libraries, and they do not guarantee a more accurate final answer. Check the algorithm’s conditioning and the precision required by the output contract before changing numeric types.

Decimal for Arbitrary Precision

decimal.Decimal supports configurable decimal precision through its context. The context controls significant digits for arithmetic operations, so it can be raised for a calculation and restored afterward with localcontext().

Constructing Decimal from a float imports that float’s existing binary approximation, as the long output in the example shows. Increasing context precision later cannot restore digits discarded during conversion.

Decimal is useful when decimal rounding rules matter, but it is not a drop-in replacement for every float operation. Its arithmetic follows decimal contexts, and combining Decimal with float directly raises TypeError. Convert values deliberately at the boundary, and choose a rounding mode that matches the domain rather than relying on an unstated business rule.

A context precision setting counts significant digits, not digits after the decimal point. Use quantize() when the requirement is a fixed scale such as two places. Keep the original input separately when trailing zeroes communicate a measurement scale or a reporting requirement.

Decimal handles scalar arithmetic. For a large table of decimal values, first determine whether exact decimal semantics are required for every operation. A binary array library can be faster to integrate with numerical algorithms, while decimal objects may have different performance and interoperability trade-offs.

NumPy for Up to 113-Bit Precision

NumPy longdouble can provide extended binary precision on some systems. The observed dtype and finfo metadata in the example depend on the platform.

On platforms where longdouble uses an extended format with 113 bits of significand precision, it can retain more binary digits than float64. Other platforms may make longdouble equivalent to float64 or use a different extended format. Test the operations your program needs on the deployment target.

NumPy arrays are useful when calculations operate over many values and the selected dtype is supported by the functions in use. Create the array from source strings or higher-precision inputs when decimal digits matter. Confirm downstream libraries do not cast values back to float64.

A float128 label does not guarantee 128 significant bits. Some platforms use a 128-bit storage layout with fewer significand bits, so check finfo fields and documented platform support.

Compare High-Precision Options in Python

The table matches common numeric requirements with their trade-offs.

OptionGood fitWatch for
floatGeneral scientific calculations and approximate measurementsBinary rounding and finite binary64 range on standard builds
DecimalDecimal inputs and specified decimal roundingContext precision, explicit conversions and slower object arithmetic
FractionExact rational values from integers or textNumerator and denominator growth in repeated operations
NumPy longdoubleArray calculations where the target platform offers wider precisionPlatform-dependent format and possible casts in other libraries

For example, a financial amount entered as 12.30 should usually begin as Decimal text if decimal rounding is part of the requirement. A probability assembled from exact counts can stay as a Fraction until conversion is needed. A measured sensor reading may use float when its uncertainty is larger than binary rounding error.

Switching types without checking input conversion, rounding rules and downstream operations can preserve the original error source.

Edge Cases and Precision Limits

NaN and infinity are valid float values, so arithmetic can produce them without raising an exception. Check for them before sorting or storing results in a system that requires finite numbers.

CaseSymptomFix
NaNvalue == value returns FalseCheck with math.isnan(value)
Infinitymath.isfinite(value) returns FalseReject or handle it under a domain rule
Mixed Decimal and float arithmeticTypeErrorConvert inputs to one numeric family first

I ran python3 invalid_decimal.py with x and got decimal.InvalidOperation (exit status 1). The input is not valid Decimal text. Catch that exception and return an input error instead of comparing traceback text.

from decimal import Decimal

print(Decimal('x'))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
Decimal InvalidOperation traceback from a nonnumeric string
Traceback with the failing Decimal constructor call.

Precision is the granularity of a representation. Accuracy describes how closely a result matches its intended quantity. More digits can reduce arithmetic rounding but cannot remove measurement uncertainty or model error.

Conclusion

A numeric result needs two checks: how its input was created and what the next operation assumes. The examples show how those checks change the reading of a result.

Python’s Decimal documentation covers contexts and rounding. The Fraction documentation, round reference and NumPy’s data type guide describe the alternatives shown here. For adjustable binary precision, the mpmath guide documents mpf and mp.dps, and project owners should verify that its operations fit the calculation before adding it.

For related tasks, see AskPython’s guides to rounding a float to the nearest tenth and formatting floating-point output.

FAQ

These answers cover common questions about Python float precision and choosing a numeric type.

Does Python have a double data type?

Python has no separate built-in double keyword. Its built-in float is normally a 64-bit IEEE 754 double-precision value.

Is 3.14 a float or a double in Python?

3.14 is a Python float literal. On standard builds, that float uses double-precision binary64 representation.

Should I use float or Decimal?

Use float for general numerical work. Use Decimal constructed from strings when decimal arithmetic and controlled rounding matter.

How do I read a double value in Python?

Use float(input_text) to parse ordinary numeric input. Python returns its built-in float type, which is normally double precision.

Gurpreet Kaur
Gurpreet Kaur
Articles: 37