views:

53

answers:

2

I have been using Math.Round(myNumber, MidpointRounding.ToEven) in c# to do my server-side rounding, however, the user needs to know 'live' what the result of the server-side operation will be which means (avoiding an ajax request) creating a javascript method to replicate the MidpointRounding.ToEven method used by c#.

MidpointRounding.ToEven is Gaussian/Bankers rounding, a very common rounding method for accounting systems described here.

Does anyone have any experience with this? I have found examples online but they do not round to a given number of decimal places...

A: 

You could use Ajax to actually execute this rounding on the server side which will make it simpler to maintain your code base, because you will only have one single code. If you decide to change it, you'll only change it once. No need for (maybe even complex) javascript updates.

Robert Koritnik
surely you'd only update the javascript on the server and that'd automatically propogate to all clients when they next visit the page..
Will
@Will: I'm not talking about clients. I'm talking about server and client code. If you decide to change the logic of calculation, you'll have to change both. But if you use Ajax, you'dd only have to change server code.
Robert Koritnik
With bankers rounding be a very well defined thing, would you change it ever? That and if you did, would having it in two functions be less work than an ajax thing? probably. But really, if you have a new definition of bankers rounding, you could publish papers!
Will
+1  A: 
function evenRound(num, decimalPlaces) {
    var d = decimalPlaces || 0;
    var m = Math.pow(10, d);
    var n = d ? num * m : num;
    var i = Math.floor(n), f = n - i;
    var r = (f == 0.5) ? ((i % 2 == 0) ? i : i + 1) : Math.round(n);
    return d ? r / m : r;
}

alert(evenRound(1.5)); // 2
alert(evenRound(2.5)); // 2
alert(evenRound(1.535, 2)); // 1.54
alert(evenRound(1.525, 2)); // 1.52
Tim Down
Sweetly done! Works for negatives too. +2 :P
Jimbo