上代码, 真正四舍五入. 不是四舍六入五成双 看懂鼓掌
function round2(val, len) { len = (len || len === 0)? len : 2; var flag = Math.pow(10, len); if (!val || isNaN(val)) { return def; } val = parseFloat(val); if (val.toString().indexOf('.') == -1) { return val; } var decimal = val.toString().split('.')[1]; var n = val * flag if (decimal.charAt(len) >= 5) { return Math.floor((n + 1)) / flag; } else { return Math.floor(n) / flag; } }
round2(3.145,2) 3.15 round2(3.135,2) 3.14 round2(3.134,2) 3.13 round2(3.1345,3) 3.135 round2(3.1344,3) 3.134