with-precision

added
1.0

ns
clojure.core

type
macro

(with-precision precision & exprs)

Sets the precision and rounding mode to be used for BigDecimal operations.

Usage: (with-precision 10 (/ 1M 3))
or:    (with-precision 10 :rounding HALF_DOWN (/ 1M 3))

The rounding mode is one of CEILING, FLOOR, HALF_UP, HALF_DOWN,
HALF_EVEN, UP, DOWN and UNNECESSARY; it defaults to HALF_UP.

                ;; The "M" suffix denotes a BigDecimal instance
;; http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html

user=> (with-precision 10 (/ 1M 6))
0.1666666667M

user=> (.floatValue 0.1666666667M)
0.16666667

            
                ;; This may come in handy for example when you use JDBC to grab data
;; from a database, and numbers comes in as BigDecimal. Notice the
;; following ArithmeticException, and solution:

(/ 2M 3M)                    ; => ArithmeticException
(with-precision 2 (/ 2M 3M)) ; => 0.67M

;; To make this error more searchable, here's what it is, exactly:
;;
;; Non-terminating decimal expansion; no exact representable decimal result. 
;; java.lang.ArithmeticException: Non-terminating decimal expansion; no exact ;; representable decimal result.