Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round number down to nearest power of ten

Tags:

javascript

I have a number and I need to round it down to the nearest power of ten. It seems like this should be possible without a whole bunch of if statements or using recursion or looping, but I don't know the most elegant way to do it. In case it's unclear what I mean, here are some examples:

f(1) === 1
f(5) === 1
f(15) === 10
f(43) === 10
f(456) === 100
f(999) === 100

To clarify: I do not need nearest multiple of 10 (not: 10, 20, 30...), but nearest power of ten (10, 100, 1000...).

Edit: To my knowledge this is not a duplicate question. Please stop closing as a duplicate of a question asking about rounding to the nearest multiple of ten. This question is unrelated to the linked question, because it asks about rounding to the nearest power of ten. If you would like to close this question as a duplicate, please find and link a duplicate question. The question which is currently linked was commented about 30 seconds after I posted the question, by someone who did not read the entire question and merely commented complaining about it being a duplicate. That person has since deleted his comments (after realizing he was wrong), although you can see comments by myself and someone else both pointing out that this is not a duplicate.

like image 456
Matthias Avatar asked Oct 08 '17 16:10

Matthias


3 Answers

You could take the logarithm of 10 and take the integer value for the power of 10.

function f(v) {
    return Math.pow(10, Math.floor(Math.log10(v)));
}

console.log(f(1));   //   1
console.log(f(5));   //   1
console.log(f(15));  //  10
console.log(f(43));  //  10
console.log(f(456)); // 100
console.log(f(999)); // 100
like image 173
Nina Scholz Avatar answered Nov 17 '22 12:11

Nina Scholz


Simply get the length of the number(by converting Number into a string) and then generate the result by taking the power of 10(where the exponent is length - 1).

function generateNum(v) {
  return Math.pow(10, v.toString().length - 1);
}

var data = [1, 5, 15, 43, 456, 456, 999];


data.forEach(function(v) {
  console.log(generateNum(v));
})

function generateNum(v) {
  return Math.pow(10, v.toString().length - 1);
}

FYI : In case number includes decimal part then you need to avoid decimal part by taking the floor value.

function generateNum(v) {
  return Math.pow(10, Math.floor(v).toString().length - 1);
}
like image 3
Pranav C Balan Avatar answered Nov 17 '22 14:11

Pranav C Balan


Here's a variant that works for negative numbers:

let round10 = v => Math.pow(10, Math.floor(Math.log10(Math.abs(v)))) * Math.pow(-1, v < 0);
like image 2
Alex Lenail Avatar answered Nov 17 '22 12:11

Alex Lenail