liveBook · Manning

Number rounding

As explained in Clojure: The Essential Reference

Numeric rounding is the approximation of a value to the finite precision available in its numerical representation.

Number rounding approximates values to the finite precision available in a numerical representation. In Clojure, explicit precision matters when calculations use BigDecimal or when floating-point error can accumulate. section 5.11 section 5.13

Use with-precision to evaluate BigDecimal expressions with a chosen precision and rounding mode. Its contract accepts a nonnegative integer precision, an optional mode such as :rounding DOWN or HALF_EVEN, and one or more expressions. section 5.11

Controlling a non-terminating result

(/ 22M 7) raises an ArithmeticException because the decimal expansion does not terminate. (with-precision 4 (/ 22M 7)) returns 3.143M. A financial calculation can also promote inputs with bigdec, round a share quantity DOWN, and return a contractually chosen numeric type.

Practical considerations:

  • BigDecimal values can spread through an expression, so boundary functions may promote inputs, calculate with explicit precision, and convert results according to their contract. section 5.11

How Clojure: The Essential Reference covers it

How deep it goes
Defines precision, rounding modes, numeric contagion, exceptions, and financial examples without developing rounding internals.
Examples
Demonstrates 22/7, floating-point subtraction error, and share-price calculations with explicit rounding.
What it assumes
Assumes basic Clojure arithmetic and numeric types while teaching BigDecimal precision, rounding modes, and representation error.
What you can do after
Apply it via with-precision to choose precision and rounding behavior for BigDecimal expressions.
How it connects
Connects BigDecimal, floating-point arithmetic, numeric precision, type promotion, and financial calculations.

Also explained in

Compare how 4 books explain number rounding →

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.