Home > Backend Development > Python Tutorial > How Can I Reliably Preserve Two Decimal Places in Floating-Point Numbers in Python?

How Can I Reliably Preserve Two Decimal Places in Floating-Point Numbers in Python?

Patricia Arquette
Release: 2024-12-25 19:25:13
Original
834 people have browsed it

How Can I Reliably Preserve Two Decimal Places in Floating-Point Numbers in Python?

Preserving Two Decimal Points in Floating-Point Numbers

When working with floating-point numbers, it's often desirable to limit them to a specific number of decimal points. However, simply using the round() function can lead to unexpected results as witnessed with the following behavior:

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
Copy after login

This occurs because floating-point numbers have limitations in representing all numbers accurately. The values stored in memory are not always the same as those displayed.

Understanding Floating-Point Precision

Double precision floating-point numbers, used in Python, have approximately 16 digits of precision. This means that numbers like 13.95 are represented in a way similar to:

125650429603636838/(2**53)
Copy after login

When applying the round() function, the result is still the same floating-point value, internally represented with the same limitations.

>>> 125650429603636838/(2**53)
13.949999999999999
Copy after login

Alternative Methods for Limiting Decimal Points

If displaying only two decimal places is essential, consider these alternatives:

  • Using Integers and Scaling: Represent values in cents instead of dollars and divide by 100 to convert.
  • Using Fixed-Point Decimal: Utilize modules like decimal to store and operate on fixed-point numbers with specified precision.

Examples:

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

# Using decimal module
>>> import decimal
>>> a = decimal.Decimal('13.946')
>>> a.quantize(decimal.Decimal('.01'))
Decimal('13.95')
Copy after login

The above is the detailed content of How Can I Reliably Preserve Two Decimal Places in Floating-Point Numbers in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template