2016-01-15 62 views
4

我需要下面的C#代碼轉換爲德爾福:帶5位小數位的貨幣?

decimal XYZ = decimal.Round(dataset123.XYZ, 5, MidpointRounding.AwayFromZero); 

結果將在MSSQL數據庫保存到浮點型字段。

當我在Delphi中使用double時,有幾個問題,因爲它沒有固定的十進制。另外,當保存到ADO數據庫中時,數據庫查看器通常會顯示非常長的數字,因爲它的數字太多。此外,似乎有一個舍入方法問題,舍入不總是「遠離零」完成。

我想現在解決最嚴重的問題。我需要一個5位貨幣,但德爾福只有數據類型currency有4位數。擁有5位數值是這類項目/業務流程的重要要求。

在一些互聯網的來源,我讀到人們談論這樣的代碼:

var 
    x: Decimal[5,3] 

但是這句法不適用於我。我與德爾福2007年工作。

有什麼我可以做得到一個5位數的固定小數?

+0

寫基於Int64的自己的類型 –

+2

試試我的[十進制](http://rvelthuis.de/programs/decimals.html)類型。它與.NET Decimal類型兼容,所以你的代碼應該很容易移植。 –

+0

@DavidHeffernan我該怎麼做?我試過'輸入C = 0.00000 .. 99999.99999;',但這不起作用。我不明白爲什麼Integer可以幫助定義小數。 –

回答

1

下面是使用大衛赫弗南的建議,告訴你如何開始的一些代碼:

unit UnitMyCurrency; 

interface 

uses 
    System.SysUtils; 

type 
    TMyCurrency = record 
    Value : int64; 

    class operator implicit(pValue : integer) : TMyCurrency; 
    class operator implicit(pValue : single) : TMyCurrency; 
    class operator implicit(pValue : TMyCurrency) : single; 

    class operator Add(p1 : TMyCurrency; p2 : TMyCurrency) : TMyCurrency; 
    class operator Subtract(p1 : TMyCurrency; p2 : TMyCurrency) : TMyCurrency; 

    class operator NotEqual(p1 : TMyCurrency; p2 : single) : boolean; 
    const 
    cFactor = 100000; 
    end; 

implementation 

{ TMyCurrency } 

class operator TMyCurrency.implicit(pValue: integer): TMyCurrency; 
begin 
    Result := pValue * cFactor; 
end; 

class operator TMyCurrency.implicit(pValue: single): TMyCurrency; 
begin 
    Result := round(pValue * cFactor); 
end; 

class operator TMyCurrency.Add(p1, p2: TMyCurrency): TMyCurrency; 
begin 
    Result := TMyCurrency(p1.Value + p2.Value); 
end; 

class operator TMyCurrency.implicit(pValue: TMyCurrency): single; 
begin 
    Result := pValue.Value/cFactor; 
end; 

class operator TMyCurrency.NotEqual(p1: TMyCurrency; p2: single): boolean; 
begin 
    Result := TMyCurrency(p2).Value <> p1.Value; 
end; 

class operator TMyCurrency.Subtract(p1, p2: TMyCurrency): TMyCurrency; 
begin 
    Result.Value := p1.Value - p2.Value; 
end; 

procedure Test; 
var 
    v1, v2, v3 : TMyCurrency; 
begin 
    v1 := 5.12345; 
    v2 := 6.00000; 
    if (v1 + v2) <> 11.12345 then 
    begin 
    raise Exception.Create('Error Message'); 
    end; 
end; 

end. 

顯然,這是不完整的,但完成後,你將有一個新的類型這就是你所需要的,並且你有完全的控制權。

以下顯示瞭如何使用重載操作符。這是西雅圖,但一切都沒有改變自2007年以來

http://docwiki.embarcadero.com/RADStudio/en/Operator_Overloading_(Delphi)

+0

@David Heffernan - 感謝您的編輯 - 抱歉讓您的姓名錯誤。 – Dsm

-3

簡單的方法是使用變量CurrencyDecimals。 類似的東西:

var 
    price: Double; 

begin 
    price:= 1234.56789; 
    CurrencyDecimals := 5; 
    ShowMessage('Price = '+Format('%m', [price])); 
end; 
+5

這是一個二進制浮點類型,提交者需要定點小數。 –

+0

是和:)?我仍然認爲實現提問者想要的最好方法是將該值轉換爲想要的定點值。此外 這留下了價值如何存儲和他的視覺表示。 –

+2

我不確定你是否完全理解二進制浮點和定點十進制之間的區別 –