You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.
Answer from Rex Logan on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › floatingpoint.html
15. Floating-Point Arithmetic: Issues and Limitations — Python 3.14.5rc1 documentation
Since at least 2000, almost all machines use IEEE 754 binary floating-point arithmetic, and almost all platforms map Python floats to IEEE 754 binary64 “double precision” values.
Top answer
1 of 16
2332

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.
2 of 16
838

There are new format specifications, String Format Specification Mini-Language:

You can do the same as:

"{:.2f}".format(13.949999999999999)

Note 1: the above returns a string. In order to get as float, simply wrap with float(...):

float("{:.2f}".format(13.949999999999999))

Note 2: wrapping with float() doesn't change anything:

>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
Discussions

[Python] Adding floating point number causes precision issues for some numbers but not othera.
See here . This is specific to a widely-used way of representing decimal numbers. This isn't specific to Python. More on reddit.com
🌐 r/learnprogramming
8
0
January 9, 2024
Python 3 Float Decimal Points/Precision - Stack Overflow
I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using float() to convert a line into a float, and raising a ValueError if that fails. I am storing ... More on stackoverflow.com
🌐 stackoverflow.com
Scientific Precision in Python?

Matlab uses floats too. Why would writing matlab code solve floating point issues that you get in python?

Have you checked what kind of floating point noise your application can tolerate? This isn't a python issue. It's going to apply so long as you choose to use a computer.

More on reddit.com
🌐 r/learnpython
24
3
April 18, 2022
python - Is floating point arbitrary precision available? - Stack Overflow
Just for fun and because it was really easy, I've written a short program to generate Grafting numbers, but because of floating point precision issues it's not finding some of the larger examples. ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › decimal.html
decimal — Decimal fixed-point and floating-point arithmetic
For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625'). The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value.
🌐
GeeksforGeeks
geeksforgeeks.org › python › precision-handling-python
Precision Handling in Python - GeeksforGeeks
December 19, 2025 - Given a number, the task is to control its precision either by rounding it or formatting it to a specific number of decimal places. For Example: Input: x = 2.4 Output: Integral value = 2 Smallest integer greater than x = 3 Greatest integer smaller ...
🌐
Medium
medium.com › @goldengrisha › understanding-floating-point-precision-issues-in-python-a-practical-guide-5e17b2f14057
Understanding Floating-Point Precision Issues in Python: A Practical Guide | by Gregory Kovalchuk | Medium
September 25, 2024 - For example, the decimal number `0.1` cannot be precisely stored as a binary floating-point number. Instead, it is approximated by a fraction that is as close as possible within the limits of the system’s precision. To see this in action, consider the following Python code:
🌐
Reddit
reddit.com › r/learnprogramming › [python] adding floating point number causes precision issues for some numbers but not othera.
r/learnprogramming on Reddit: [Python] Adding floating point number causes precision issues for some numbers but not othera.
January 9, 2024 -

I'm not sure if this is a problem with my IDE or if its a Python issue but when I add a floating point number, take 3.14 for example, to some numbers I get a lot of additional 0s.

y = 3.14
y1 = 3.14 + 1
print(3.14)

Output:
4.140000000000001

I noticed this issue occurs when I add 1 to 4 but if I add 5 I get 8.14 instead, without all of the 0s.

Why does this only happen when adding certain numbers?

🌐
AskPython
askpython.com › home › double precision floating values in python
Double precision floating values in Python - AskPython
April 10, 2025 - Python’s built-in float data type provides up to 15 digits of decimal precision. While sufficient for most applications, some numerical computations require even higher precision.
Find elsewhere
🌐
Mimo
mimo.org › glossary › python › float
Python Floats: Coding Essentials | Learn Now
... Dividing two numbers results ... third = 1 / 3 # Results in a float, approximately 0.3333 · The return value of such operations is always a float, ensuring precision even when the inputs are whole numbers....
🌐
ZetCode
zetcode.com › python › decimal
Python Decimal - high-precision calculations in Python with Decimal
In the following example, we also use the mpmath module, which is a library for arbitrary-precision floating-point arithmetic. ... We need to install mpmath first. ... #!/usr/bin/python from decimal import Decimal, getcontext import math import mpmath getcontext().prec = 50 mpmath.mp.dps = 50 num = Decimal(1) / Decimal(7) num2 = mpmath.mpf(1) / mpmath.mpf(7) print(" math.sqrt: {0}".format(Decimal(math.sqrt(num)))) print("decimal.sqrt: {0}".format(num.sqrt())) print(" mpmath.sqrt: {0}".format(mpmath.sqrt(num2))) print('actual value: 0.3779644730092272272145165362341800608157513118689214')
🌐
Shiksha
shiksha.com › home › it & software › it & software articles › programming articles › precision handling in python
Precision Handling in Python - Shiksha Online
October 31, 2022 - The celi() function belongs to python’s math module, therefore to use it we need to first import the math module into our program. ... Returns: The ceil() function returns the smallest integer greater than the floating point number. Example: ...
🌐
LabEx
labex.io › tutorials › python-how-to-handle-python-float-precision-425669
How to handle Python float precision | LabEx
In Python, floats are implemented using the IEEE 754 double-precision binary floating-point format.
🌐
Luc
anh.cs.luc.edu › python › hands-on › 3.1 › handsonHtml › float.html
1.14. Decimals, Floats, and Floating Point Arithmetic — Hands-on Python Tutorial for Python 3
More on that in String Formats for Float Precision. It is sometimes important to know the numeric type of the result of a binary operation. Any combination of +, -, and * with operands of type int produces an int. If there is an operation /, or if either operand is of type float, the result is float. Try each in the Shell (and guess the resulting type): [1] ... Exponentiation is finding powers. In mathematical notation, (3)(3)(3)(3)=34. In Python there is no fancy typography with raised exponent symbols like the 4, so Python uses ** before a power: Try in the Shell:
🌐
Real Python
realpython.com › how-to-python-f-string-format-float
How to Format Floats Within F-Strings in Python – Real Python
April 24, 2024 - To use Python’s format specifiers ... You achieved this by adding the format specifier .2f into the replacement field. The 2 is the precision, while the lowercase f is an example of a presentation type....
🌐
Reddit
reddit.com › r/learnpython › scientific precision in python?
r/learnpython on Reddit: Scientific Precision in Python?
April 18, 2022 -

When the matter is precision - like, really precise - floats are crap. Even double precision can be a gamble when working with scientific data - very small and very large numbers.

What are the best options when I need to work with numbers on the -15th and +20th orders of magnitude? (at the same time, mind you)

Is the decimal.py module precise enough for those sorts of calculations? If not, is it possible to get precise results with python or will I have to write some matlab modules to crunch my numbers?

Top answer
1 of 5
72

In the standard library, the decimal module may be what you're looking for. Also, I have found mpmath to be quite helpful. The documentation has many great examples as well (unfortunately my office computer does not have mpmath installed; otherwise I would verify a few examples and post them).

One caveat about the decimal module, though. The module contains several in-built functions for simple mathematical operations (e.g. sqrt), but the results from these functions may not always match the corresponding function in math or other modules at higher precisions (although they may be more accurate). For example,

from decimal import *
import math

getcontext().prec = 30
num = Decimal(1) / Decimal(7)

print("   math.sqrt: {0}".format(Decimal(math.sqrt(num))))
print("decimal.sqrt: {0}".format(num.sqrt()))

In Python 3.2.3, this outputs the first two lines

   math.sqrt: 0.37796447300922719758631274089566431939601898193359375
decimal.sqrt: 0.377964473009227227214516536234
actual value: 0.3779644730092272272145165362341800608157513118689214

which as stated, isn't exactly what you would expect, and you can see that the higher the precision, the less the results match. Note that the decimal module does have more accuracy in this example, since it more closely matches the actual value.

2 of 5
11

For this particular problem, decimal is a great way to go, because it stores the decimal digits as tuples!

>>> a = decimal.Decimal(9999999998)
>>> a.as_tuple()
DecimalTuple(sign=0, digits=(9, 9, 9, 9, 9, 9, 9, 9, 9, 8), exponent=0)

Since you're looking for a property that is most naturally expressed in decimal notation, it's a bit silly to use a binary representation. The wikipedia page you linked to didn't indicate how many "non-grafting digits" may appear before the "grafting digits" begin, so this lets you specify:

>>> def isGrafting(dec, max_offset=5):
...     dec_digits = dec.as_tuple().digits
...     sqrt_digits = dec.sqrt().as_tuple().digits
...     windows = [sqrt_digits[o:o + len(dec_digits)] for o in range(max_offset)]
...     return dec_digits in windows
... 
>>> isGrafting(decimal.Decimal(9999999998))
True
>>> isGrafting(decimal.Decimal(77))
True

I think there's a good chance the result of Decimal.sqrt() will be more accurate, at least for this, than the result of math.sqrt() because of the conversion between binary representation and decimal representation. Consider the following, for example:

>>> num = decimal.Decimal(1) / decimal.Decimal(7)
>>> decimal.Decimal(math.sqrt(num) ** 2) * 7
Decimal('0.9999999999999997501998194593')
>>> decimal.Decimal(num.sqrt() ** 2) * 7
Decimal('1.000000000000000000000000000')
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter09.02-Floating-Point-Numbers.html
Floating Point Numbers — Python Numerical Methods
Instead of utilizing each bit as ... \(f\), which is the coefficient of the exponent. Almost all platforms map Python floats to the IEEE754 double precision - 64 total bits....
🌐
PythonHow
pythonhow.com › how › limit-floats-to-two-decimal-points
Here is how to limit floats to two decimal points in Python
x = 3.14159265 # Format x as a string with two decimal points y = "{:.2f}".format(x) print(y) # Output: "3.14"The format function takes a format string as the first argument and the value to format as the second argument. The format string specifies the desired formatting for the value, and ...
🌐
Python.org
discuss.python.org › python help
Questions about the Python Language and Floating Point - Python Help - Discussions on Python.org
December 6, 2022 - -Does Python have floating point errors with its float number type? -If it does, is there any switch or kind of software option to turn off these error possibilities, at the level of the language? -I have heard that P…