Boxuan
Boxuan

Reputation: 5157

JavaScript flooring number to order of magnitude

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.

Upvotes: 23

Views: 7735

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

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.

Upvotes: 39

Related Questions