Skip to content

Equality with different precision #61

Open

Description

@gwenya

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.

Activity

  1. nowackipawel commented on Feb 9, 2022

    @nowackipawel

    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)]
    ); 
    
  2. nowackipawel commented on Feb 9, 2022

    @nowackipawel

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

  3. rtheunissen commented on Feb 9, 2022

    @rtheunissen
    Contributor

    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

  4. speller commented on Jul 12, 2023

    @speller

    I'm voting for this fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions