|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转新大榭论坛!
您需要 登录 才可以下载或查看,没有账号?注册
x
decimal 模块为快速正确舍入的十进制浮点运算提供了支持。4 G$ [. m9 w4 c
// 它提供float数据类型有以下几个优点:
R4 a$ ^% r5 `2 ^% `! l5 \- x E- 十进制数字可以准确表示:数字如 1.1 和 2.2 在二进制浮点中没有精确的表示。 K0 V Y' @- {" \% d
- >>> 1.1 + 2.29 q. ]% v( b K& n
- 3.3000000000000003
/ j9 ], L/ \7 b5 x - >>> from decimal import Decimal7 W5 H( l+ f% M& W5 V3 ]" E
- >>> Decimal('1.1') + Decimal('2.2')
+ S& p( n6 o9 P# }7 G9 m4 ]# H. i - Decimal('3.3')
复制代码- 精确性延续到算术中。
- 保留尾随零以表示重要性。8 k) p5 \& g/ \3 R- ]8 \5 u
- >>> 1.20*1.30
6 a, d' U6 S2 S0 ]1 f4 w+ i - 1.56; L9 t7 L( E$ |* f+ ]
- >>> Decimal('1.20')*Decimal('1.30')
- ]' h; j& y5 ^3 g/ H9 ^; F - Decimal('1.5600')
复制代码 常用方法
8 o7 L/ b4 g5 ^% s5 O% Q' n) ]- class decimal.Decimal(value="0", context=None)
复制代码 3 y! }; E1 b; w
- 可以传递给Decimal整型或者字符串参数,但不能是浮点数据,因为浮点数据本身就不准确。
, X8 W& E# c ]- >>> from decimal import *2 q! `( z0 q5 x7 o9 s; Z
- >>> Decimal(1.1) + Decimal(2.2)
, B! f q- ~# c( e$ ~0 Y9 D: i - Decimal('3.300000000000000266453525910'2 H1 R8 M8 K" ^& @
- >>> Decimal('1.1') + Decimal('2.2')7 R5 v& a% l. f* p9 Y7 I
- Decimal('3.3')
复制代码
) k. q; C" a0 T1 ]' j9 [ - 通过设定有效数字,限定结果样式。' _) p+ s# h) I, U/ [# e2 g9 F
- >>> getcontext().prec = 6! \6 x& w& s; q7 C$ {2 j. [/ b+ p
- >>> Decimal(1)/Decimal(7)' y& x p% s7 o" l( F$ ^8 Q
- Decimal('0.142857')# G8 k+ p7 h, l2 x9 }0 n2 G6 y
- >>> getcontext().prec = 28
8 G/ m6 V+ R! \0 S" u( Z - >>> Decimal(1) / Decimal(7)
7 d1 m( `% {) L: I) E) a - Decimal('0.1428571428571428571428571429')
复制代码
( i' I* Z& Q5 `6 m, L. W6 ~ - 四舍五入,保留几位小数。
5 x$ I2 T5 X7 y+ z% P% V- >>> Decimal('12.3456').quantize(Decimal('0.00'))0 z5 `0 x2 D5 w' h4 A E
- Decimal('12.35')" |6 Q. e+ h7 r9 V. ~/ \) Z
- >>> Decimal('12.3456').quantize(Decimal('1.1'))
+ J5 n% A A7 a G( n2 a9 F6 P! a - Decimal('12.3')
复制代码
e5 q# q' v2 z5 o1 Q
|
|