title | description |
---|---|
Floating-point cheat sheet for Python |
Tips for using floating-point and decimal numbers in Python |
Almost all platforms map Python floats to IEEE 754 double precision.
f = 0.1
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
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
几乎所有平台把 Python 的浮点映射成 IEEE 754 双精度。
f = 0.1
Python 有 arbitrary-precision 小数类型,称为 Decimal
,这个类型在 decimal
模块中,它同样允许选择 取整模式.
a = Decimal('0.1')
b = Decimal('0.2')
c = a + b # 返回 Decimal 表示的精确的 0.3
得到字符串:
"%.2f" % 1.2399 # 返回 "1.24"
"%.3f" % 1.2399 # 返回 "1.240"
"%.2f" % 1.2 # 返回 "1.20"
打印到标准输出:
print "%.2f" % 1.2399 # 只是使用打印和字符串格式化
特殊的 取整模式 和其它参数可以在一个 Context 对象中定义:
getcontext().prec = 7