Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round down to the nearest power of 10?

I can't even find search keywords for this. Please consider this code:

float inputValue = getInputValue();
float resultValue;

if (inputValue < 0.1f) {
    resultValue = 0.01f;
}
else if (inputValue < 1.0f) {
    resultValue = 0.1f;
}
else if (inputValue < 10.0f) {
    resultValue = 1.0f;
}
else {
    resultValue = 10.0f;
}

and so on. There must be a more elegant way to do this. I guess the solution is easy, but I try to find a way now for 2 hours and read about round, ceil, floor...can't find it.

Has anyone an idea?

like image 883
user1840267 Avatar asked Jan 10 '23 23:01

user1840267


1 Answers

powf(10.0f, floorf(log10f(value)))
like image 124
Spook Avatar answered Jan 19 '23 00:01

Spook