Home >Backend Development >Python Tutorial >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
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)
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
Alternative Methods for Limiting Decimal Points
If displaying only two decimal places is essential, consider these alternatives:
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')
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!