Open In App

Gaussian/banker’s rounding in JavaScript

The task is to implement the Gaussian/banker’s rounding with the help of JavaScript. Here, few approaches are discussed.

Approach 1: Get the d value(which tells the digits to which we need to round off). Calculate the m(pow(10, d)). Then shift the decimal after the digits we want to round off(if d=2, shift it to 2 places right of n). Then get the floor value of n(which is i) and calculate the difference between the original value and floor value of n. Check the condition whether the value which is going to return is i or i+1, if the condition matches else return i(store the value in r). If d=0 return r else return r/m.

Approach 2: Get the d value(which tells the digits to which we need to round off). Shift the decimal to right of n according to d. Then get the round value of n(which is r). If the absoluteValue(n) % 1 == 0.5 and if the r is even return r else r-1 and if absoluteValue(n) % 1 != 0.5 then return r.


Article Tags :