liveBook · Manning

Precision

As explained in Clojure: The Essential Reference

Numeric precision is the amount of numerical detail a representation or calculation can retain.

Numeric precision is the amount of numerical detail a representation or calculation can retain. In Clojure, precision becomes practical when floating-point rounding, BigDecimal arithmetic, money, or large-scale computation can make small errors accumulate. section 5.11 section 5.13

Precision affects arithmetic in several connected ways:

  • double uses binary floating-point representation, so ordinary decimal fractions can produce visible artifacts such as 0.6100000000000001. section 5.11
  • BigDecimal preserves decimal-oriented calculation but can throw ArithmeticException for non-terminating results unless a precision and rounding mode are supplied. section 5.11
  • Clojure’s numeric contagion rules roughly promote results toward the most precise operand, but explicit design is safer when precision matters. section 5.13

Controlling decimal division

(/ 22M 7) raises an ArithmeticException because the decimal expansion does not terminate. Wrapping the operation controls the result: (with-precision 4 (/ 22M 7)) returns 3.143M. A rounding mode can make the policy explicit, as in (with-precision 5 :rounding DOWN ...). section 5.11

Listing 5.7. → Arbitrary Precision Math, BigDecimal Precision, Precision Settings
(with-precision [precision & exprs])

Browse the compact contract for with-precision, including precision bounds, supported rounding modes, and wrapped expressions. section 5.11

How Clojure: The Essential Reference covers it

How deep it goes
Explains floating-point artifacts, BigDecimal contexts, rounding, and contagion rules, while noting exceptions to rough promotion behavior.
Examples
Demonstrates 22/7, decimal subtraction artifacts, account-share calculations, and a hash function using unchecked integer arithmetic.
What it assumes
Assumes familiarity with Clojure arithmetic and numeric literals while defining BigDecimal behavior and precision contexts through examples.
What you can do after
Apply it via with-precision, BigDecimal promotion, explicit rounding, and deliberate numeric-type choices.
How it connects
Connects precision with BigDecimal, floating-point arithmetic, numeric types, rounding modes, and numeric overflow.

Also explained in

Compare how 9 books explain precision →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.