如何使javascript舍入对值中的位数敏感



假设我们有一个数组[0.09870499],我们想四舍五入数组值,所以:[0.1000100]?

我试过什么:

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

然而,它看起来相当丑陋。。。但它正是我所需要的。

我使用了几个函数来舍入数字,它们可能很有用。

function roundTo2(value){
return (Math.round(value * 100) / 100);
}

function roundResult(value, places){
    var multiplier = Math.pow(10, places);
    return (Math.round(value * multiplier) / multiplier);
}

很明显,你需要对数字进行四舍五入并放入数组/提取、四舍五进、放回-效率不如其他人的答案是

假设您希望四舍五入到最接近的10次方(并且您的499舍入到100的示例不正确):

var rounded = myArray.map(function(n) {
    return Math.pow(10, Math.ceil(Math.log(n) / Math.LN10));
});

从给定的例子来看,@DuckQueen似乎想要四舍五入到最接近的10次方。

这是算法

1. Represent each number N in scientific notation S. Lets say S is n*10^x
2. Let A =(N - (10 power x)) and B=((10 pow x+1) - N)
3. if A<B N = 10^x otherwise N=10^(x+1)

对于情况A==B ,您可以采取这样或那样的方式

将其用于步骤1:

  • 如何将数字转换为科学记数法

最新更新