Floating-point cheat sheet for Python
Floating-Point Types
Almost all platforms map Python floats to IEEE 754 double precision.
f = 0.1
Decimal Types
Python has an arbitrary-precision decimal type named Decimal
in the decimal
module, which also allows to choose the rounding mode.
a = Decimal('0.1')
b = Decimal('0.2')
c = a + b # returns a Decimal representing exactly 0.3
How to Round
To get a string:
"%.2f" % 1.2399 # returns "1.24"
"%.3f" % 1.2399 # returns "1.240"
"%.2f" % 1.2 # returns "1.20"
To print to standard output:
print("%.2f" % 1.2399) # just use print and string formatting
Specific rounding modes and other parameters can be defined in a Context object:
getcontext().prec = 7
Resources
© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)