Uploaded image for project: 'Clojure'
  1. CLJ-1118

inconsistent numeric comparison semantics between BigDecimal and other Numerics

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Major
    • Resolution: Completed
    • Affects versions: Release 1.5, Release 1.4
    • Fix versions: Release 1.6
    • Labels:
    • Approval:
      Ok
    • Patch:
      Code and Test

      Description

      BigDecimal does not have consistent comparison semantics with other numeric types.

      user> *clojure-version*
      {:major 1, :minor 5, :incremental 1, :qualifier nil}
      user> (== 2.0 2.0M)
      true
      user> (== 2 2.0M)
      false                  <-- this one is not like the others
      user> (== 2 2.0)
      true
      user> (== 2N 2.0)
      true
      user> (== 2 (double 2.0M))
      true
      user> (== 1.0M 1.00M)
      false    ;; potentially surprising
      

      Patch: clj-1118-v7.patch

      Approach: Change equiv for BigDecimals so that instead of using BigDecimal.equals(), it uses BigDecimal.compareTo() and checks the return value is equal to 0.

      The javadoc for these methods explicitly states that BigDecimal.equals() will treat values that are otherwise equal numerically, but differ in scale, as not equal. They also say that BigDecimal.compareTo() will return 0 for such BigDecimals.

      Doing this also changes the behavior of = when comparing BigDecimal values to other numbers. hash should be consistent with =, so now hash should return the same value for all numerically equal BigDecimal values. This patch modifies hasheq() to return the same value for all numerically equal BigDecimal values, by calling BigDecimal.stripTrailingZeros() on them before hashing. This change also will make 1.0M == 1.00M which was not true before.

      Screened by: Alex Miller

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              alex+import import
            • Votes:
              1 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: