Skip to content

Rounding Modes

When a result can't be represented exactly at the requested scale or precision, a RoundingMode decides how it's rounded. BigDecimal.js implements all eight of Java's modes, with identical semantics.

js
import { Big, RoundingMode } from 'bigdecimal.js'

Big('2.345').setScale(2, RoundingMode.HALF_UP)   // '2.35'
Big('2.345').setScale(2, RoundingMode.HALF_EVEN) // '2.34'
Big('2.345').setScale(2, RoundingMode.FLOOR)     // '2.34'

The eight modes at a glance

ModeRounds…Ties
UPaway from zero
DOWNtoward zero (truncate)
CEILINGtoward +∞
FLOORtoward −∞
HALF_UPto nearestaway from zero
HALF_DOWNto nearesttoward zero
HALF_EVENto nearestto the even neighbor ("banker's")
UNNECESSARYasserts exactnessthrows if rounding is needed

Worked table (rounding to an integer)

This is the JDK's canonical table — each input rounded to zero decimal places. Because correctness here is defined as "matches Java", these are exactly the results BigDecimal.js produces:

InputUPDOWNCEILINGFLOORHALF_UPHALF_DOWNHALF_EVEN
5.56565656
2.53232322
1.62121222
1.12121111
1.01111111
-1.0-1-1-1-1-1-1-1
-1.1-2-1-1-2-1-1-1
-1.6-2-1-1-2-2-2-2
-2.5-3-2-2-3-3-2-2
-5.5-6-5-5-6-6-5-6
Ctrl / ⌘ + Enter

Which one should I use?

  • HALF_UP — what people mean by "round". Good default for display.
  • HALF_EVEN — banker's rounding; removes the systematic upward bias of HALF_UP over many values. The standard for financial aggregates and the default of IEEE-754.
  • DOWN / FLOOR — truncation; e.g. flooring shares of money so you never over-allocate.
  • UP / CEILING — e.g. billing that always rounds a partial unit up.
  • UNNECESSARY — a guard: use it when you expect the operation to be exact and want a thrown error if your assumption is ever wrong.
js
Big('2.50').setScale(1, RoundingMode.UNNECESSARY).toString() // '2.5'  — already exact
Big('2.55').setScale(1, RoundingMode.UNNECESSARY)            // throws — rounding was needed

Where rounding modes apply

Any operation that can lose precision takes a RoundingMode (or a MathContext, which bundles precision + mode):

  • setScale(scale, roundingMode)
  • divide(divisor, scale, roundingMode) and divideWithMathContext(divisor, mc)
  • round(mc) — round to a MathContext's precision
  • The formatters: toFixed, toExponential, toPrecision (default HALF_UP)

Released under the Apache-2.0 License.