Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  104] [ 2]  / answers: 1 / hits: 6692  / 10 Years ago, wed, may 28, 2014, 12:00:00

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.


More From » javascript

 Answers
22

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.


[#44976] Tuesday, May 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;