Python开发中怎么实现货币格式化的需求
Admin 2022-07-13 群英技术资讯 530 次浏览
python开发中时长到货币格式化的问题,一般情况下可以使用locale模块。但是这个模块使用起来不是那么顺手,今天我为大家介绍一个很好用的方法。
直接上代码。。。
from decimal import * def moneyfmt(value, places=2, curr='', sep=',', dp='.',pos='', neg='-', trailneg=''): """Convert Decimal to a money formatted string. places: required number of places after the decimal point curr: optional currency symbol before the sign (may be blank) sep: optional grouping separator (comma, period, space, or blank) dp: decimal point indicator (comma or period) only specify as blank when places is zero pos: optional sign for positive numbers: '+', space or blank neg: optional sign for negative numbers: '-', '(', space or blank trailneg:optional trailing minus indicator: '-', ')', space or blank >>> d = Decimal('-1234567.8901') >>> moneyfmt(d, curr='$') '-$1,234,567.89' >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') '1.234.568-' >>> moneyfmt(d, curr='$', neg='(', trailneg=')') '($1,234,567.89)' >>> moneyfmt(Decimal(123456789), sep=' ') '123 456 789.00' >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') '<0.02>' """ value = Decimal(value) q = Decimal(10) ** -places # 2 places --> '0.01' sign, digits, exp = value.quantize(q).as_tuple() result = [] digits = map(str, digits) build, next = result.append, digits.pop if sign: build(trailneg) for i in range(places): build(next() if digits else '0') build(dp) if not digits: build('0') i = 0 while digits: build(next()) i += 1 if i == 3 and digits: i = 0 build(sep) build(curr) build(neg if sign else pos) return ''.join(reversed(result)) print moneyfmt('1234.45',sep=',', dp='.')
结果:
1,234.45
很简单吧。。。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
opencv矩形轮廓矫正怎样实现,及相关问题怎样解决,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解一下,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋友就往下看吧!
这篇文章主要为大家介绍了Python中字典有关的常见函数的使用方法,以及字典遍历的方法。文中通过示例代码为我们进行了详细介绍,对学习Python字典有一定帮助,需要的可以参考一下
这篇文章主要为大家详细介绍了python实现简单通讯录管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要介绍了Python自然语言处理之切分算法详解,文中有非常详细的代码示例,对正在学习python的小伙伴们有非常好的帮助,需要的朋友可以参考下
这篇文章主要介绍了利用Python绘制多种风玫瑰图,风玫瑰是由气象学家用于给出如何风速和风向在特定位置通常分布的简明视图的图形工具,下文绘制实现详情,需要的小伙伴可以参考一下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008