Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript flooring number to order of magnitude

Tags:

javascript

I want to floor any integers >= 10 according to its order of magnitude. For instance,

15 -> 10
600 -> 100
8,547 -> 1,000
32,123 -> 10,000
3,218,748 -> 1,000,000
544,221,323,211 -> 100,000,000,000
....

I was thinking parsing the int to string and count how many digits are there, then set the new string to 1 + a bunch of zeros and convert back to number.

function convert(n) {
    nStr = n.toString();
    nLen = nStr.length;
    newStr = "1" + Array(nLen).join("0");
    return parseInt(newStr);
}

Is there a more mathematical way to do this? I want to avoid converting between int and str because it might waste a lot of memory and disk space when n is huge and if I want to run this function a million times.

like image 642
Boxuan Avatar asked May 28 '14 16:05

Boxuan


1 Answers

So you're looking for the order of magnitude.

function convert(n) {
    var order = Math.floor(Math.log(n) / Math.LN10
                       + 0.000000001); // because float math sucks like that
    return Math.pow(10,order);
}

Simple ^_^ Math is awesome! Floating point imprecisions, however, are not. Note that this won't be completely accurate in certain edge cases, but it will do its best.

like image 166
Niet the Dark Absol Avatar answered Sep 29 '22 23:09

Niet the Dark Absol