DuckQueen
DuckQueen

Reputation: 802

How to make javascript round sensitive to number of digits in value?

Say we had an array [0.09, 870, 499] and we want to get array values round so: [0.1, 1000, 100]?

What have I tried:

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

Yet it seems quite ugly... yet it does exactly what I need.

Upvotes: 0

Views: 311

Answers (3)

abipc
abipc

Reputation: 1035

From the given example it looks like @DuckQueen wants to round off to nearest power of 10..

Here is the algo -

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)

You may assume one way or the other for the case A==B

Use this for Step 1:

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

Assuming that you wish to round up to the nearest power of 10 (and that your example of 499 rounding to 100 is incorrect):

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

Upvotes: 1

null
null

Reputation: 3517

I use a couple of functions for rounding numbers, they might be useful.

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);
}

You'll obviously need to round numbers and put into the array / extract, round, put back - not as efficient as someone elses answer may be

Upvotes: 1

Related Questions