Equality with different precision
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.
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)]
);
I thought trim will do the job, but as long as precision in one case is higher it is not working:/
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
I'm voting for this fix!