這是@ soegaard的一個很好的解決方案。 這裏是一個小的變化,使得它爲小數點工作:
bankers_round(n:number, d:number=0) {
var x = n * Math.pow(10, d);
var r = Math.round(x);
var br = (((((x>0)?x:(-x))%1)===0.5)?(((0===(r%2)))?r:(r-1)):r);
return br/Math.pow(10, d);
}
雖然它 - 這裏有一些測試:
console.log(" 1.5 -> 2 : ", bankers_round(1.5));
console.log(" 2.5 -> 2 : ", bankers_round(2.5));
console.log(" 1.535 -> 1.54 : ", bankers_round(1.535, 2));
console.log(" 1.525 -> 1.52 : ", bankers_round(1.525, 2));
console.log(" 0.5 -> 0 : ", bankers_round(0.5));
console.log(" 1.5 -> 2 : ", bankers_round(1.5));
console.log(" 0.4 -> 0 : ", bankers_round(0.4));
console.log(" 0.6 -> 1 : ", bankers_round(0.6));
console.log(" 1.4 -> 1 : ", bankers_round(1.4));
console.log(" 1.6 -> 2 : ", bankers_round(1.6));
console.log(" 23.5 -> 24 : ", bankers_round(23.5));
console.log(" 24.5 -> 24 : ", bankers_round(24.5));
console.log(" -23.5 -> -24 : ", bankers_round(-23.5));
console.log(" -24.5 -> -24 : ", bankers_round(-24.5));
好問題。是[這個腳本](http://dansnetwork.com/2009/11/30/round-half-to-even-with-javascript/)你發現的例子之一?它看起來可能是合適的,但我不是這方面的專家:-) – 2010-06-24 10:26:00
它接近!但不幸的是沒有與負數工作 - 我會做一些改變,並在這裏發佈......謝謝:) – Jimbo 2010-06-27 11:12:17