Categories
JavaScript Answers

How to Do Gaussian/Banker’s Rounding in JavaScript?

Spread the love

To do Gaussian/Banker’s rounding in JavaScript, we can create our own function to do the rounding.

For instance, we write:

const isEven = (n) => {
  return (0 === (n % 2));
};

const bankersRound = (x) => {
  const r = Math.round(x);
  return (((((x > 0) ? x : (-x)) % 1) === 0.5) ? ((isEven(r)) ? r : (r - 1)) : r);
};

console.log(bankersRound(1))
console.log(bankersRound(1.5))
console.log(bankersRound(2.5))

We first create the isEven function to return whether the number n is an even number.

Then we create the bankersRound function to round the number.

In the function, we first round the number x with Math.round .

Then we check if x is bigger than 0.

If it is, then we return x .

Otherwise, we return -x .

And we check if that number divided by 1 has 0.5 as the remainder.

If it does, we check if the number if even with isEven .

If it is, we return r .

Otherwise, we return r — 1 .

If x ends with .5, then we also return r .

Therefore, we see the first console log logs 1 and the other 2 logs 2.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *