2014/10/17

Delphi 的四捨五入方法

Delphi 以往的「四捨六入五成雙」 -- Round
要改成常用的「四捨五入」,坊間有一大票使用很彆扭的方式來達成。

但 Delphi 的 Math 單元早已經有這樣的函式了:

Math.SimpleRoundTo

可是這樣的命名規則很不討喜,所以我們可以再重新封裝一下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
uses
  Math;

function RoundA(A_Float: Extended): Integer; overload;
begin
  Result := Trunc(Math.SimpleRoundTo(A_Float, 0));  // 取整數部分即可
end;

function RoundA(A_Float: Extended; A_Digit: Integer=-2): Extended; overload;
begin
  Result := Math.SimpleRoundTo(A_Float, A_Digit);
end;

沒有留言:

張貼留言