Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing issues in DUnit CheckEquals with Currency Field Values

Tags:

delphi

dunit

I'm comparing some currency values in DUnit but it is not working at all on my machine (work on others, but not on mine).

An example:

CheckEquals(16.65, SomeCurrencyFieldValue);

Raises:

expected: <16,65> but was: <16,65>

if do the following the comparison then works:

var
  Temp: Currency;
begin
  Temp := 16.65;
  CheckEquals(Temp, SomeCurrencyFieldValue);

The question is: Why the comparison doesn't work when I pass the value direct to the CheckEquals method?

like image 794
Fabio Gomes Avatar asked Jan 28 '09 18:01

Fabio Gomes


3 Answers

The issue has to do with how Currency values get converted to Extended values at run time versus how floating-point literals get converted to Extended values at compile time. If the conversion isn't the same in both cases, then the values passed to CheckEquals may not compare equal.

It would be worth checking in the debugger's CPU window whether either of the values goes through an intermediate Double value on its way to Extended in preparation for the function call. An extra conversion would affect the exact value of the result.

Another thing to consider is that 16.65 is not representable exactly as an Extended value, but it is representable exactly as a Currency value. Although Currency is classified as a floating-point type, it is really a fixed-point scaled 64-bit integer. That's probably grounds for requesting an additional CheckEquals overload in DUnit that takes that into account.

like image 154
Rob Kennedy Avatar answered Nov 09 '22 15:11

Rob Kennedy


I see that there is only CheckEquals() for extended values in the Delphi 2007 dUnit sources. But you could use this one:

procedure CheckEquals(expected, actual: extended; delta: extended;
  msg: string = ''); overload; virtual;

and give a proper delta for currency values.

like image 2
mghie Avatar answered Nov 09 '22 13:11

mghie


I encountered the very same problem. It looks like some DLLs modify a FPU (processor) control word. This explains why the error does not occur always. It can appear suddenly when some new tests, which use other units than the previous test suite, are added. Or if a software update installs bad DLLs. I have written about on my blog:

  • Why 1.99 suddenly no longer equals 1.99

I also found that Delphi contains a SafeLoadLibrary function, which restores the control word.

This also explains why the original question mentions that the problem is machine-dependent.

like image 1
mjn Avatar answered Nov 09 '22 14:11

mjn