在Delphi中,为了实现货币数值运算中的严格精度要求,内部把货币类型数据当作一个放大10000倍的64位整数来处理。这样根据64位整数的范围,可以得出货币类型Currency的范围是 [-922337203685477.5807; 922337203685477.5807]。
货币类型一个最常见的应用场景是金额大写转换,网上都是一些先将货币转字符串后再对字符串处理的代码,而且有些方法在有些情况下不满足金额大写规范,这里给出一个直接转换的方法。
unit TU2.Helper.Currency;
interface
function CurrencyToChineseCapitalCharacter(const AValue: Currency; const ADecimals: Cardinal=4): string;
function CurrencyToString(const AValue: Currency; const ADecimals: Cardinal=4): string;
implementation
uses System.SysUtils, System.Math;
function CurrencyRound(var U: UInt64; const ADecimals: Cardinal): Integer; inline;
var
W: UInt64;
begin//Bankers-rounding
Result := 4-ADecimals;
if Result<0 then
Result := 0
else if Result>0 then
begin
case Result of
1:begin //li
DivMod(U, 10, U, W);
if (W > 5) or ((W = 5) and Odd(U)) then
Inc(U);
end;
2:begin //fen
DivMod(U, 100, U, W);
if (W > 50) or ((W = 50) and Odd(U)) then
Inc(U);
end;
3:begin //jiao
DivMod(U, 1000, U, W);
if (W > 500) or ((W = 500) and Odd(U)) then
Inc(U);
end;
4:begin //yuan
DivMod(U, 10000, U, W);
if (W > 5000) or ((W = 5000) and Odd(U)) then
Inc(U);
end;
end;
end;
end;
function Cur