我尝试使用这个:
//var value = "39.99";
//var value = "0.255";
var list = ["39.99", "0.255", "0.306", "0.645", "2.505", "5.726", "9.649", "9.999", "10.01", "0.155", "0.355", "10.05", "14.75", "14.02", "2.405", "14.54","2.485"];
var result;
for( i in list ){
//result = processRounding(parseFloat(list[i]).toFixed(3));
//result = parseFloat(list[i]).toFixed(2);
result = test(parseFloat(list[i]).toFixed(3), 2);
console.log("RESULT["+i+"]: "+ format("#,##0.00", result));
}
function test(value, precision) {
var precision = precision || 0,
neg = value < 0,
power = Math.pow(10, precision),
value = Math.round(value * power),
integral = String((neg ? Math.ceil : Math.floor)(value / power)),
fraction = String((neg ? -value : value) % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
return precision ? integral + '.' + padding + fraction : integral;
}
function processRounding (value){
//console.log( Math.ceil(value*100) + " " + Math.ceil(value*100) / 2);
var remainder = parseFloat(value % 1).toFixed(2);
var floor = parseInt(Math.floor(value));
console.log(floor + " " + remainder);
if(Math.floor(value) != 0 && Math.floor(value) > 10){
if( parseFloat(remainder) > 0.50 || parseFloat(remainder) > 0.05 ){
console.log("CEIL");
value = Math.ceil(value*10)/10;
}else{
value = value;
}
}else{
if( parseFloat(remainder) > 0.50 || parseFloat(remainder) > 0.05 ){
console.log("ROUND");
value = Math.round(value*100)/100;
}else{
value = value;
}
}
return value;
}
[这里的jsFiddle ]
但是我看到的问题是,当值类似于"2.405"
它所做的事情时,无论我是在我的 jsfiddle 示例中使用函数test
还是函数,都将其设为“2.40”。processRounding
关于如何将结果变成 2.41 的任何想法?从技术上讲,由于最后一位数字是“5”,因此它应该向上取整。
更新
使用result = test(parseFloat(list[i]).toFixed(3), 2);
var list = ["39.99", "0.255", "0.306", "0.645", "2.505", "5.726", "9.649", "9.999", "10.01", "0.155", "0.355", "10.05", "14.75", "14.02", "2.405", "14.54","2.485"];
会导致这个:
RESULT[0]: 39.99
RESULT[1]: 0.26
RESULT[2]: 0.31
RESULT[3]: 0.65
RESULT[4]: 2.51
RESULT[5]: 5.73
RESULT[6]: 9.65
RESULT[7]: 10.00
RESULT[8]: 10.01
RESULT[9]: 0.16
RESULT[10]: 0.36
RESULT[11]: 10.05
RESULT[12]: 14.75
RESULT[13]: 14.02
RESULT[14]: 2.40
RESULT[15]: 14.54
RESULT[16]: 2.49
请注意,在列表中有一个“2.405”值,在结果 [14] 中它是“2.40”,它应该在 2.41 中,对吗?