假设我们有一个数组 [0.09, 870, 499] 并且我们想要得到数组值,所以:[0.1, 1000, 100]?
我尝试了什么:
var logarithmicRound = function(val) {
var degree = Math.round(Math.log(val) / Math.LN10);
if(Math.pow(10, degree) - val > val) {
--degree;
}
return Math.pow(10, degree);
};
console.log(logarithmicRound(0.05));
console.log(logarithmicRound(0.7));
console.log(logarithmicRound(49));
console.log(logarithmicRound(50));
console.log(logarithmicRound(400));
console.log(logarithmicRound(800));
// prints
//0.1
//1
//10
//100
//100
//1000
然而它看起来很丑陋......但它正是我所需要的。