Python开发中怎么实现货币格式化的需求
Admin 2022-07-13 群英技术资讯 575 次浏览
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中Canny边缘检测的实现,边缘检测一般是识别目标图像中亮度变化明显的像素点,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要介绍了Django如何创作一个简单的最小程序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于内置模块OS如何打造SHELL端文件处理器的相关内容,下面一起来看一下,希望对大家有帮助。
这篇文章主要介绍了pygame实现井字棋之第一步绘制九宫格,文中有非常详细的代码示例,对正在学习python的小伙伴们有非常好的帮助,需要的朋友可以参考下
matplotlib内置了众多预定义的颜色映射表,使用这些颜色映射表可以为用户提供更多的颜色建议,为用户节省大量的开发时间。pyplot模块中提供了colormaps()函数用于查看所有可用的颜色映射表,示例代码及运行结果如下。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008