Python开发中怎么实现货币格式化的需求
Admin 2022-07-13 群英技术资讯 948 次浏览
这篇文章给大家介绍了“Python开发中怎么实现货币格式化的需求”的相关知识,讲解详细,步骤过程清晰,有一定的借鉴学习价值,因此分享给大家做个参考,感兴趣的朋友接下来一起跟随小编看看吧。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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
一个图片里边绘制多个图像是绘图中的常见需求,下面这篇文章主要给大家介绍了关于python绘制子图技巧之plt.subplot、plt.subplots及坐标轴修改的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
对于中文乱码的情况很多朋友在编程过程中都有遇到,因此这篇文章就主要给大家分享的是有关python出现中文乱码怎样解决的方法。小编觉得挺实用的,因此分享给大家做个参考,感兴趣的朋友就继续往下看吧。
这篇文章主要介绍了Python 生成器yield原理及用法,yield 是实现生成器方法之一,当函数使用yield方法,则该函数就成为了一个生成器,更多相关资料需要的小伙伴可以参考一下下面文章内容
这篇文章主要介绍了python实现sql布尔盲注的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
这篇文章主要介绍python读取大文件的方法,小编觉得挺实用的,因此分享给大家做个参考,感兴趣的朋友可以了解一下,希望大家阅读完这篇文章能有所收获,接下来小编带着大家一起了解看看。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008