A tiny utility function (like - literally; the function is a one-liner) to perform symmetric rounding to integer Numbers.
npm install --save symmetric-round
If your project only "speaks" CommonJS, you can use:
const symmetricRound = require('symmetric-round');
...but if you're transpiling with (or otherwise have) full ES6 support:
import symmetricRound from 'symmetric-round';'
Why this package exists?
- when the input value is exactly half way between two integer Numbers, the result is the Number value that is closer to positive infinity.
This means that the standard states that the absolute value of rounding negative and positive values is asymmetric by definition; e.g.:
-99... and ...
In practice - this leads to all sorts of hard-to-pinpoint bugs in your code like:
- calculating discount reimbursements might get a different value than what the original discount was
- drawing charts may be "a pixel off" when they reside on the the negative side of chart origo, etc.
...and those are just examples of the situations I have personally witnessed. All because
Math.round() does not work the way I was taught at school back in the day when dinosaurs roamed the Earth.
So... Let's round numbers symmetrically instead!
This "tie-breaking method" of rounding Numbers to Integers is known by many names, such as "round half away from zero", "round half towards nearest infinity", "commercial rounding" or "symmetric rounding".
With "symmetric rounding", the positive and negative numbers are treated symmetrically and therefore the method is free of overall positive/negative bias (assuming the original numbers are positive or negative with equal probability).
Furthermore, this method of rounding is often used for currency conversions and price roundings etc.
;; // 100; // -100
In real life, this is insignificant since:
-0 === +0; // true-0 === 0; // true+0 === 0; // true
However, it is good to keep in mind that:
Object; // falseObject; // falseObject; // true