財務系統、發票列印、支票列印常需將數字金額轉為中文大寫(壹貳參肆伍陸柒捌玖拾佰仟萬億元角分厘),防止竄改。
FormatFloat('0.00', Value))。function NumberToChineseCurrency(Value: Currency): string;
const
CN_DIGITS: array[0..9] of string = ('零', '壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖');
CN_UNITS: array[0..15] of string = (
'分', '角', '元',
'拾', '佰', '仟', '萬',
'拾', '佰', '仟', '億',
'拾', '佰', '仟', '兆'
);
var
StrVal: string;
DotPos, i, UnitIdx: Integer;
Ch: Char;
HasNonZero: Boolean;
begin
Result := '';
// 格式化為兩位小數,確保角、分位存在
StrVal := FormatFloat('0.00', Value);
DotPos := Pos('.', StrVal);
if DotPos = 0 then Exit;
// 從小數點左邊(元)往左、右邊(角分)往右,統一由低位往高位處理
// 這裡採用字串反轉邏輯:將小數點移除,字串反轉,索引即為 UnitIdx
StrVal := StringReplace(StrVal, '.', '', [rfReplaceAll]);
// 現在 StrVal 為整數字串,個位在最右邊,需反轉
for i := Length(StrVal) downto 1 do
begin
UnitIdx := Length(StrVal) - i; // 0=分, 1=角, 2=元, 3=拾...
Ch := StrVal[i];
if Ch <> '0' then
begin
Result := CN_DIGITS[Ord(Ch) - Ord('0')] + CN_UNITS[UnitIdx] + Result;
HasNonZero := True;
end
else if HasNonZero and (UnitIdx = 2) then // 元位必須顯示「零元」?
Result := CN_DIGITS[0] + CN_UNITS[UnitIdx] + Result
else if HasNonZero and (UnitIdx in [6, 10]) then // 萬、億位補零
Result := CN_DIGITS[0] + CN_UNITS[UnitIdx] + Result;
end;
// 移除開頭多餘的「零」
while (Length(Result) >= 2) and (Copy(Result, 1, 1) = '零') do
Delete(Result, 1, 1);
// 特殊情況:純零金額
if Result = '' then Result := '零元整';
end;
ShowMessage(NumberToChineseCurrency(1234567890.12));
// 輸出:壹拾貳億參仟肆佰伍拾陸萬柒仟捌佰玖拾元壹角貳分
Currency 型別避免浮點誤差。