C# log base 10 and rounding up to nearest power of 10?
if i have a number between 100 and 1000 i want to get the value 3 because 10^3 = 1000. Likewise, if i had a number between 10 and 100 i would want to get the value 2, because 10^2 is 100.
Incase you're wondering, its to do with calculating a probability and i always need to divide through by 10^value, to keep the probability between 0 a开发者_如何学JAVAnd 1. For example if i calculate 9256, i need to divide through by 10^4, so that i get a probability of 0.92
I'm not sure how to do the rounding up and how to do the base 10, could someone please help?
Math.Ceiling(Math.Log10(x))
Why can't you just take the log of the number and then round it up? Log 9256 will give you 3.966, round it up to 4 (add one and integerize it if you want), then divide by 10 to the power of 4... you practically answered the question yourself.
Using the logarithm will work, but you'll also need to consider the rest of the calculation. Dividing out the powers of 10 may be simpler for you:
double Scale(double x)
{
if(x <= 0} { return 0; }
while(x > 1.0)
{
x /= 10.0;
}
return x;
}
精彩评论