Delphiで切り捨て、四捨五入、切り上げする際にどんな関数を使っていますか?
Floor、Trunc、Round、SimpleRound、Ceil などを使っていることと思う。
これらの関数は、戻り値の範囲がLongintの範囲であったり、正負での扱いが対照でなかったりするので作ってみた。
x に丸めたい値を、Factor に丸め位置(小数点以下桁数:小数部第一位は1、整数部1桁目は-1)を与える。
※Delphi7 以降には、標準で通常の四捨五入関数 (SimpleRoundTo) が付いている。
- 切り捨て
-
function MyRoundDown(x: Currency; Factor: Integer): Currency; var dFactor: Double; begin Factor := Factor -1; dFactor := IntPower(10, Factor); if Factor < 0 then Factor := Factor +1; if x >= 0 then Result := Int(x * dFactor) / dFactor else Result := Int((x * dFactor) + 0.9) / dFactor; end;
- 四捨五入
-
function MySimpleRound(x: Currency; Factor: Integer): Currency; var Sgn: Integer; dFactor: Double; begin if x >= 0 then Sgn := 1 else Sgn := -1; if Factor < 0 then Factor := Factor +1; Factor := Factor -1; dFactor := IntPower(10, Factor); Result := Int(Abs(x) * dFactor + 0.5) / dFactor * Sgn; end;
- 切り上げ
-
function MyRoundUp(x: Currency; Factor: Integer): Currency; var dFactor: Double; begin Factor := Factor -1; dFactor := IntPower(10, Factor); if Factor < 0 then Factor := Factor +1; if x >= 0 then Result := Int((x * dFactor) + 0.9) / dFactor else Result := Int(x * dFactor) / dFactor; end;