我们在开发过程中,有时候需要把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等数据结构进行了功能的扩展。

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

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

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

实例扩展:

用python实现把数字人民币金额转换成大写的脚本程序

# -*- coding: utf-8 -*-
def Num2MoneyFormat( change_number ):
  """
  .转换数字为大写货币格式( format_word.__len__() - 3 + 2位小数 )
  change_number 支持 float, int, long, string
  """
  format_word = ["分", "角", "元",
        "拾","百","千","万",
        "拾","百","千","亿",
        "拾","百","千","万",
        "拾","百","千","兆"]

  format_num = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
  if type( change_number ) == str:
    # - 如果是字符串,先尝试转换成float或int.
    if '.' in change_number:
      try:  change_number = float( change_number )
      except: raise ValueError, '%s  can\'t change'%change_number
    else:
      try:  change_number = int( change_number )
      except: raise ValueError, '%s  can\'t change'%change_number

  if type( change_number ) == float:
    real_numbers = []
    for i in range( len( format_word ) - 3, -3, -1 ):
      if change_number >= 10 ** i or i < 1:
        real_numbers.append( int( round( change_number/( 10**i ), 2)%10 ) )

  elif isinstance( change_number, (int, long) ):
    real_numbers = [ int( i ) for i in str( change_number ) + '00' ]

  else:
    raise ValueError, '%s  can\'t change'%change_number

  zflag = 0            #标记连续0次数,以删除万字,或适时插入零字
  start = len(real_numbers) - 3
  change_words = []
  for i in range(start, -3, -1): #使i对应实际位数,负数为角分
    if 0 <> real_numbers[start-i] or len(change_words) == 0:
      if zflag:
        change_words.append(format_num[0])
        zflag = 0
      change_words.append( format_num[ real_numbers[ start - i ] ] )
      change_words.append(format_word[i+2])

    elif 0 == i or (0 == i%4 and zflag < 3):  #控制 万/元
      change_words.append(format_word[i+2])
      zflag = 0
    else:
      zflag += 1

  if change_words[-1] not in ( format_word[0], format_word[1]):
    # - 最后两位非"角,分"则补"整"
    change_words.append("整")

  return ''.join(change_words)

print Num2MoneyFormat( 343.45 )
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com