python实现人性化显示金额数字

472次阅读
没有评论

python实现人性化显示金额数字

我们在开发过程中,有时候需要把float,int型等数字作为金额类型数字显示会出现很多问题,比如float会显示成 965868.4599999,int型没有小数位等各种各样的问题。我们需要进行转换显示,才能保证阅读人性化。

方法一:

这里只贴上主要代码:

# 金额人性化
def humanized_amount(self, *args, **kwargs):
    """
    金额人性化,保留二位小数,再进行人性化显示

    compel强制二位,默认True,
    """
    if not CheckData(self.__mark).is_int_or_float:
        return {"code": "0001", "msg": "必须传入数字", "data": None}
    else:
        figure = float(self.__mark)

    # 保留二位小数
    figure = "{:.2f}".format(figure)

    # 人性化显示
    figure = "{:,}".format(float(figure))

    if kwargs.get("compel", True):
        # 进行处理,保留二位小数,如果不足二位补领
        figure_list = figure.split(".")
        if len(figure_list[1]) == 1:
            figure += "0"

    return figure

方法二:利用xToolkit库

安装方法:

pip install xToolkit  -i  http://pypi.douban.com/simple --trusted-host pypi.douban.com

xToolkit库是我自己封装的python内置库的一个扩展库.把python的datetime,string,list,dist,xthread等数据结构进行了功能的扩展。里面好用的功能比较多,可以前往 https://blog.csdn.net/qq_22409661/article/details/108531485 查看具体用法。

使用方法比较简单,一行代码即可搞定

# 金额人性化,保留二位小数

xstring.dispose(3.0).humanized_amount(compel=False)
xstring.dispose("3.0").humanized_amount(compel=True)
xstring.dispose(37787841.902).humanized_amount(compel=False)
xstring.dispose("37787841.902").humanized_amount(compel=True)
xstring.dispose(378978989).humanized_amount(compel=False)
xstring.dispose("378978989").humanized_amount(compel=True)

>>3.0
>>3.00
>>37,787,841.9
>>37,787,841.90
>>378,978,989.0
>>378,978,989.00
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-10发表,共计1389字。
新手QQ群:570568346,欢迎进群讨论 Python51学习