Skip to content

Instantly share code, notes, and snippets.

@sspboyd
Created June 5, 2019 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sspboyd/942611f69d50f7caeed703a407db01fb to your computer and use it in GitHub Desktop.
Save sspboyd/942611f69d50f7caeed703a407db01fb to your computer and use it in GitHub Desktop.
Rounding up and rounding down to the nearest order of base 10 magnitude.
// Some example code for rounding up and rounding down to the nearest order of base 10 magnitude.
// Thanks to this thread for pointing me in the right direction
// https://stackoverflow.com/questions/7906996/algorithm-to-round-to-the-next-order-of-magnitude-in-r
void setup() {
int i = 1200;
println("i = "+ i);
println("---");
println("log(i): "+log(i));
println("log10(i): " + log10(i));
println("---");
println("ceil(log10(i)): " + ceil(log10(i)));
println("floor(log10(i)): " + floor(log10(i)));
println("---");
println("pow(10, ceil(log10(i))): " + pow(10, ceil(log10(i))));
println("pow(10, floor(log10(i))): " + pow(10, floor(log10(i))));
/*
i = 1200
---
log(i): 7.090077
log10(i): 3.0791812
---
ceil(log10(i)): 4
floor(log10(i)): 3
---
pow(10, ceil(log10(i))): 10000.0
pow(10, floor(log10(i))): 1000.0
*/
}
// Calculates the base-10 logarithm of a number
float log10 (int x) {
return (log(x) / log(10));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment