Skip to content

top-quark/rounding.js

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 

rounding.js

Exact rounding to a specified number of decimal places with a choice of rounding algorithms

Usage

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

About

Exact rounding to a specified number of decimal places with a choice of rounding algorithms

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published