ext-decimal icon indicating copy to clipboard operation
ext-decimal copied to clipboard

Equality with different precision

Open gwenya opened this issue 4 years ago • 4 comments

Is it possible to compare two decimals while ignoring their precision, or at least ignoring it where it doesn't matter? For example new Decimal('1', 8) and new Decimal('1', 2) should be equal, and so should new Decimal('1.234', 5) and new Decimal('1.234', 20), but new Decimal('1.234', 4) and new Decimal('1.2340001', 20) should be different. The best I have at the moment is to use toFixed() with the higher of the two precisions and compare the strings, but that's a bit hard to read.

gwenya avatar Mar 22 '21 15:03 gwenya

I am experiencing the same issue. I understand why it is working like this but this is not natural what you could expect.

array(3) {
  [0]=>
  object(Decimal\Decimal)#184 (2) {
    ["value"]=>
    string(8) "0.000640"
    ["precision"]=>
    int(16)
  }
  [1]=>
  object(Decimal\Decimal)#185 (2) {
    ["value"]=>
    string(10) "0.00064000"
    ["precision"]=>
    int(18)
  }
  [2]=>
  int(-1)
}

and this is the code:

var_dump([
$transactionItem->tra_ass_id_from_amount,
$entityCryptoAddress->amount,
$transactionItem->tra_ass_id_from_amount->compareTo($entityCryptoAddress->amount)]
); 

nowackipawel avatar Feb 09 '22 13:02 nowackipawel

I thought trim will do the job, but as long as precision in one case is higher it is not working:/

nowackipawel avatar Feb 09 '22 13:02 nowackipawel

This is an easy fix if we can answer the fundamental question: how should we consider precision when evaluating equality? Looking at the Python documentation they have a few variations of compare, which is a direct mapping to mpdecimal, see https://www.bytereef.org/mpdecimal/doc/libmpdec/arithmetic.html#comparisons

I think it makes sense here to compare strictly on the value, and have the precision affect calculation and conversion only. In that case your examples of 0.000640 and 0.00064000 would be equal. I'm open to making that change in 2.x which is currently still alpha and not documented on http://php-decimal.io

rtheunissen avatar Feb 09 '22 19:02 rtheunissen

I'm voting for this fix!

speller avatar Jul 12 '23 02:07 speller