Exact rounding to a specified number of decimal places with a choice of rounding algorithms
toFixed
produces incorrect output for a large number of inputs. In contrast,
the roundTo
method provided by rounding.js implements an algorithm that
produces correct and exact results. To compare:
(1.015).toFixed(2); // 1.01 (1.015).roundTo(2); // 1.02
Unlike toFixed
, roundTo
handles arbitrarily large and small inputs:
(1.15e-26).toFixed(27); // browser-dependent; an exception is likely (1.15e-26).roundTo(27); // 0.000000000000000000000000012
rounding.js offers a choice of algorithms. The default is round half to even, but this
behaviour can be overridden by setting the Rounding.algorithm
property:
// Default algorithm is Rounding.HALF_TO_EVEN (1.25e-26).roundTo(27); // 0.000000000000000000000000012 Rounding.algorithm = Rounding.HALF_TO_PLUS_INFINITY (1.25e-26).roundTo(27); // 0.000000000000000000000000013
Rounding.HALF_TO_PLUS_INFINITY
is what Math.round
uses. To get
output similar to toFixed
set the algorithm to Rounding.HALF_AWAY_FROM_ZERO
By default, roundTo
suppresses trailing zeroes. You can override this with
a second parameter specifying the minimum number of fractional digits:
(1.1).roundTo(2); // 1.1 (1.1).roundTo(2, 2); // 1.10