with-precision

clojure.core

  • (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.

1 Example top

  • ;; 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
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:4455 top

(defmacro with-precision
  "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."
  {:added "1.0"}
  [precision & exprs]
    (let [[body rm] (if (= (first exprs) :rounding)
                      [(next (next exprs))
                       `((. java.math.RoundingMode ~(second exprs)))]
                      [exprs nil])]
      `(binding [*math-context* (java.math.MathContext. ~precision ~@rm)]
         ~@body)))
Vars in clojure.core/with-precision:
Used in 0 other vars

Comments top

No comments for with-precision. Log in to add a comment.