3

I have notice the RoundTo() function in both Delphi 7 and XE6 behave differently with some numbers and neither of them ad head to banker’s method as they said in the documentation. I pass the following number series to RoundTo(val, -4) in Delphi 7 and XE6 and they return different result for some numbers, could you explain why?

Value       Dephi7      XE6
69.72505    69.7250     69.7250
69.72515    69.7251     69.7251
69.72525    69.7252     69.7253    <-- diff
69.72535    69.7254     69.7254
69.72545    69.7254     69.7254
69.72555    69.7255     69.7255
69.72565    69.7256     69.7257    <-- diff
69.72575    69.7258     69.7258
69.72585    69.7258     69.7258
69.72595    69.7259     69.7259

This is the delphi code i used to produce the numbers above. I used the code to compile in Delphi 7 and XE6, and got different result.

procedure TForm1.Button1Click(Sender: TObject);
const
  valueList : Array[0..9] of double =
  ( 69.72505,
    69.72515,
    69.72525,
    69.72535,
    69.72545,
    69.72555,
    69.72565,
    69.72575,
    69.72585,
    69.72595
  );
var
  d : double;
  i : Integer;
begin
    Memo1.Clear;
    for i := Low(valueList) to High(valueList) do
      Memo1.Lines.Add(FloatToStr(valueList[i]) + ', ' + FloatToStr(RoundTo(valueList[i], -4)));

However, if I do it in c# using Round(val, 4), these are what I get, which is consistent to banker’s method:

Value       Round
69.72505    69.7250
69.72515    69.7252
69.72525    69.7252
69.72535    69.7254
69.72545    69.7254
69.72555    69.7256
69.72565    69.7256
69.72575    69.7258
69.72585    69.7258
69.72595    69.7260

One more thing, with the following code, which is the example from delphi documentation:

ShowMessage(FloatToStr(RoundTo(1.245, -2)));

Delphi 7 gives me 1.25 and XE6 gives me 1.24, which contradicted to their documentations. (delphi 7 doco says 1.24 but XE6 doco says 1.25).

Could you explain why?

J Kok
  • 31
  • 1
  • 1
    This is a similar question and I believe there's your answer too: http://stackoverflow.com/questions/5191235/why-is-the-result-of-roundto87-285-2-87-28 – Harriv Aug 27 '14 at 06:13
  • None of these numbers are representable in binary floating point. Bankers rounding never applies therefore. The documentation sucks big time because none of the values is representable. You need to be using a decimal data type rather than a binary data type. – David Heffernan Aug 27 '14 at 06:24

0 Answers0