金额转大写 (delphi)

按要求,只处理小数点后最大2位(角、分)

 

源码:

function TForm1.CurrencyConvert(AValue: string): string;
const
  digits: array[0..9] of string = ('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
  radices: array[0..3] of string = ('', '拾', '佰', '仟');
  bigRadices: array[0..2] of string = ('', '万', '亿');
var
  dVal, dDecimal: Double;
  iInt, i, iLen, p, zeroCount, quotient, modulus: Integer;
  cVal, cInt, d, cDecimal, cDecimal1, cDecimal2: string;
begin
  Result := '';
  if AValue.Trim <> '' then
  begin
    dVal := StrToFloatDef(AValue, 0);
    if dVal > 0 then
    begin
      iInt := Trunc(dVal);
      dDecimal := 0;
      if Pos('.', AValue) > 0 then
        dDecimal := StrToFloatDef('0.'+ Copy(AValue, Pos('.', AValue)+1, Length(AValue)), 0);
      cxLabel4.Caption := Format('整数部分:%d', [iInt]);
      cxLabel5.Caption := Format('小数部分:%s', [FloatToStr(dDecimal)]);
      //1. 处理整数部分
      cInt := '';
      if iInt > 0 then
      begin
        zeroCount := 0;
        cVal := IntToStr(iInt);
        iLen := Length(cVal);
        for i := 1 to iLen do
        begin
          p := iLen - i;
          d := Copy(cVal, i, 1);
          quotient := p div 4;
          modulus := p mod 4;
          if d = '0' then
            Inc(zeroCount)
          else
          begin
            if zeroCount > 0 then
              cInt := cInt + digits[0];
            zeroCount := 0;
            cInt := cInt + digits[StrToInt(d)] + radices[modulus];
          end;
          if (modulus = 0) and (zeroCount < 4) then
            cInt := cInt + bigRadices[quotient];
        end;
        cInt := cInt + '元';
      end
      else
        cInt := '零元';
      //2. 处理小数部分
      cDecimal := '';
      if dDecimal > 0 then
      begin
        cDecimal := FloatToStr(dDecimal)+'00';
        cDecimal := Copy(cDecimal, 1, 4); //按实际要求,只处理2位小数
        cDecimal1 := Copy(cDecimal, 3, 1);
        cDecimal2 := Copy(cDecimal, 4, 1);
        if (cDecimal1 = '0') and (cDecimal2 = '0') then
          cDecimal := ''
        else if (cDecimal1 <> '0') and (cDecimal2 = '0') then
          cDecimal := digits[StrToInt(cDecimal1)]+'角整'
        else if (cDecimal1 = '0') and (cDecimal2 <> '0') then
          cDecimal := '零'+digits[StrToInt(cDecimal2)]+'分'
        else
          cDecimal := digits[StrToInt(cDecimal1)]+'角'+digits[StrToInt(cDecimal2)]+'分';
      end;
      //
      Result := cInt;
      if cDecimal.Trim = '' then
        Result := Result + '整'
      else
        Result := Result + cDecimal;
    end;
  end;
end;

----------------------------------------------------------------------------------

客户后续又提出了新要求:

 

中间要不要加多这个“零”,重新改了一版:

 上边红色代码调一下加2行就完了:

 

 

posted on 2022-02-21 14:16  Mozzie2020  阅读(117)  评论(0编辑  收藏  举报

导航