Skip to content

Commit f53c823

Browse files
committed
新增decimal测试
1 parent 0d288f7 commit f53c823

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

test/test_decimal.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
"""
5+
@author: zhanghe
6+
@software: PyCharm
7+
@file: test_decimal.py
8+
@time: 16-6-2 下午2:56
9+
"""
10+
11+
12+
from decimal import Decimal
13+
import json
14+
15+
# float(浮点型[二进制]) 转 decimal(十进制)
16+
# float 先转 str 再转 decimal
17+
print Decimal('0.12'), repr(Decimal('0.12'))
18+
print str(Decimal('0.12')), repr(str(Decimal('0.12')))
19+
print Decimal(0.00), repr(Decimal(0.00))
20+
print Decimal(0.12), repr(Decimal(0.12))
21+
print Decimal(0.12)+Decimal(0.36), repr(Decimal(0.12)+Decimal(0.36))
22+
23+
24+
p_info = {
25+
'p_name': 'a',
26+
'p_price': Decimal('8.12')
27+
}
28+
29+
print p_info
30+
# print json.dumps(p_info) # raise TypeError(repr(o) + " is not JSON serializable")
31+
32+
33+
def __default(obj):
34+
"""
35+
支持datetime的json encode
36+
TypeError: datetime.datetime(2015, 10, 21, 8, 42, 54) is not JSON serializable
37+
:param obj:
38+
:return:
39+
"""
40+
if isinstance(obj, Decimal):
41+
return str(obj)
42+
else:
43+
raise TypeError('%r is not JSON serializable' % repr(obj))
44+
45+
print json.dumps(p_info, default=__default)
46+
47+
"""
48+
# 测试结果:
49+
0.12 Decimal('0.12')
50+
0.12 '0.12'
51+
0 Decimal('0')
52+
0.11999999999999999555910790149937383830547332763671875 Decimal('0.11999999999999999555910790149937383830547332763671875')
53+
0.4799999999999999822364316060 Decimal('0.4799999999999999822364316060')
54+
{'p_price': Decimal('8.12'), 'p_name': 'a'}
55+
{"p_price": "8.12", "p_name": "a"}
56+
57+
# 订单系统必须采用 Decimal 类型存储, 避免浮点型误差累计产生的效应
58+
"""

0 commit comments

Comments
 (0)