传统的四舍五入算法,总算测试通过了。
修复浮点数误差,修复所谓的 “四舍六入五成双” 银行进位法。
static Round(value:number, decimalCount:number):number { if(value == null) return null; let precision0 = Math.pow(10,decimalCount); let value0 = Fix999(value * precision0); let value0x = Fix999(Math.floor(value0) / precision0); let precision1 = Math.pow(10,decimalCount+1); let value1 = Fix999(value * precision1); let value1x = Fix999(Math.floor(value1) / precision1); function Fix999(x:number) { let s = x.toString(); if(s.indexOf('.') > 0) { if( s.endWith('99999') || s.endWith('99998') || s.endWith('99997') || s.endWith('99996') || s.endWith('99995') || s.endWith('99994') || s.endWith('99993') || s.endWith('99992') || s.endWith('99991') || s.endWith('99990') ) { return parseFloat(x.toFixed(decimalCount+3)); } } return x; } var s1 = value1x.toFixed(decimalCount + 1); return s1[s1.length - 1] >= '5' ? parseFloat(Fix999(value0x + 1/Math.pow(10,decimalCount)).toFixed(decimalCount)) : parseFloat(value0x.toFixed(decimalCount)); }