0

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.

3
  • 1
    Have you tried anything? Or you just hoped we'd do your homework/assignment/work for you? Commented Jul 24, 2013 at 10:39
  • 4
    Please describe the rounding rules, Why does 499 round to 100? Commented Jul 24, 2013 at 10:41
  • @AlexK. - I didn't even spot that :) Commented Jul 24, 2013 at 10:41

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.