通过Decimal('123.456')对象实例化后做 + - * / 等运算符操作计算结果不会出现精度问题。

Tips:值得注意的2点是

1.Decimal接收的入参是str,所以如果原本操作的数据类型是float需要提前强转为str。

2.decimal模块中getcontext().prec属性可以设置小数位,但是该设置是全局的,有可能会影响计算结果,比如a/b计算之前a和b已经被四舍五入2位小数了,再通过计算获得的结果必然不准,所以不如必要使用该值时劲量设大点,或者不用该设置,直接把计算结果round处理。

class RepaymentCalculator():
# 等额本金还款计划试算
def EP_cal(self, amount, apr, installments: int, start_date=None) -> list:
# getcontext().prec = 2 ,该设置会有影响mpr计算精度的风险
per_principal = Decimal(str(amount)) / Decimal(str(installments))
mpr = Decimal(str(apr)) / Decimal(str('360')) * Decimal(str('30'))
# print(float(mpr))
if start_date == None:
start_date = datetime.today()
else:
start_date = datetime.strptime(start_date, '%Y-%m-%d')
plans = []
for i in range(0, installments):
if i == 0:
installment_interest_start_date = start_date + relativedelta(months=i)
else:
installment_interest_start_date = start_date + relativedelta(months=i) + relativedelta(days=1)
plan_info = {}
principal = Decimal(str(amount)) - Decimal(str(per_principal)) * Decimal(str(i))
interest = Decimal(str(principal)) * Decimal(str(mpr))
plan_info['principal'] = round(float(per_principal), 2)
plan_info['interest'] = round(float(interest), 2)
plan_info['installment'] = i + 1
plan_info['installment_interest_start_date'] = datetime.strftime(installment_interest_start_date,
'%Y-%m-%d')
plan_info['due_date'] = datetime.strftime(start_date + relativedelta(months=i + 1),
'%Y-%m-%d')
plans.append(plan_info)
return plans

最新文章

  1. spring3 DI基础
  2. GitHub的使用记录
  3. Charles抓Android的数据包
  4. Git相关文章
  5. Reveal使用步骤
  6. java文档
  7. 【题解】【数组】【Leetcode】Merge Sorted Array
  8. 第三百零五天 how can I 坚持
  9. 【Socket规划】套接字Windows台C语言
  10. Spring+SpringMVC+MyBatis+easyUI整合优化篇(八)代码优化整理小记及个人吐槽
  11. pandas和spark的dataframe互转
  12. 二、PHP基本语法 - PHP零基础快速入门
  13. noi2018还没想好记
  14. Web前端-Vue.js必备框架(四)
  15. connect socket的超时设置
  16. RandomAccess
  17. Linux查看和注销用户(User)
  18. 【转】Git 代码行统计命令集
  19. PAT甲 1007. Maximum Subsequence Sum (25) 2016-09-09 22:56 41人阅读 评论(0) 收藏
  20. debug阶段贡献分

热门文章

  1. React使用高阶组件与Hooks实现权限拦截教程
  2. laravel phpstorm ide-helper
  3. Qt 字符串相等判断问题
  4. linux中大括号、小括号、中括号的区别和用法
  5. Windows系统运行selenium
  6. js 动态给table添加、删除行。
  7. 学术主页——朱青橙(Qingcheng Zhu)
  8. Redis缓存之spring boot 部署
  9. .net基础—多线程(二)
  10. Kubernetes基础配置管理