Skip to content

Commit

Permalink
Fix decimal coercion when already a BigDecimal
Browse files Browse the repository at this point in the history
...like when loading a ledger w/ file conn. Fixes #436.
  • Loading branch information
cap10morgan committed Apr 6, 2023
1 parent 935f543 commit ebb76de
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
13 changes: 8 additions & 5 deletions src/fluree/db/datatype.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
:cljs [fluree.db.util.cljs-const :as uc]))
#?(:clj (:import (java.time OffsetDateTime OffsetTime LocalDate LocalTime
LocalDateTime ZoneOffset)
(java.time.format DateTimeFormatter)
(java.math BigDecimal))))
(java.time.format DateTimeFormatter))))

#?(:clj (set! *warn-on-reflection* true))

Expand Down Expand Up @@ -190,16 +189,20 @@
[value]
(cond
(string? value)
#?(:clj (try (BigDecimal. ^String value) (catch Exception _ nil))
#?(:clj (try (bigdec value) (catch Exception _ nil))
:cljs (let [n (js/parseFloat value)] (if (js/Number.isNaN n) nil n)))

(integer? value)
#?(:clj (BigDecimal. ^int value)
#?(:clj (bigdec value)
:cljs value)

(float? value)
;; convert to string first to keep float precision explosion at bay
#?(:clj (BigDecimal. ^String (Float/toString value))
#?(:clj (bigdec (Float/toString value))
:cljs value)

(number? value)
#?(:clj (bigdec value)
:cljs value)

:else nil))
Expand Down
6 changes: 3 additions & 3 deletions test/fluree/db/datatype_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@
(is (= nil (coerce "foo" const/$xsd:dateTime))))

(testing "decimal"
(is (= #?(:clj (BigDecimal. "3.14") :cljs 3.14)
(is (= #?(:clj (bigdec "3.14") :cljs 3.14)
(coerce 3.14 const/$xsd:decimal)))
(is (= #?(:clj (BigDecimal. "3.14") :cljs 3.14)
(is (= #?(:clj (bigdec "3.14") :cljs 3.14)
(coerce "3.14" const/$xsd:decimal)))
(is (= #?(:clj (BigDecimal. "42.0") :cljs 42)
(is (= #?(:clj (bigdec "42.0") :cljs 42)
(coerce 42 const/$xsd:decimal)))
(is (= #?(:clj (bigdec 99.99) :cljs 99.99)
(coerce #?(:clj (bigdec 99.99) :cljs 99.99) const/$xsd:decimal)))
Expand Down

0 comments on commit ebb76de

Please sign in to comment.