How to round down to the nearest power of 10?

亡梦爱人 提交于 2019-12-07 12:04:16

问题


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?


回答1:


powf(10.0f, floorf(log10f(value)))



回答2:


I'm sure there's a much simpler way that doesn't try to work forward from first principles, but how about:

float inputValue = getInputValue();

float log10 = floorf(log10f(inputValue));
float modulo = powf(10.0f, log10);
inputValue -= fmodf(inputValue, modulo);

EDIT: actually, I think I've assumed you'd want 230 to round to 200, 0.73 to round to 0.7, etc, so this probably isn't the answer. I'm leaving it up on the basis that it may be helpful regardless.




回答3:


Your code isn't doing what you think it does. For any value less than 100 (including 0.001), resultValue will be set to 10. You'd need to check in the opposite order.

I'd start by writing down the spec for this function: Exactly what output values do you expect for what input values? Do you expect 1.0e17 for an input of 1.01e17? What if the input is 0, or -1?




回答4:


Here is a BigInteger version. I needed the next (rather than nearest) power of 10, but you see the idea:

import java.math.BigInteger;

class A {
    public static void main(String[]args) {
        System.out.println("hi");
    for (long v : new long[] {0,1,2,9,10,11,99,100,101,12345678,123456789012345678L,1234567890123456789L}) {
            System.out.println(""+v+" ==> "+nextPowerOf10(v));
        }
    }
    static long nextPowerOf10(long v) {
        return BigInteger.TEN.pow((int)Math.max(0,1+Math.floor(Math.log10(v)))).longValue();
    }
}

If you want it to behave differently on powers of 10, play with 1+Math.floor above (0/1, floor/ceil/round). By the way, what OP meant under "nearest?" Nearest on the linear or on the logarithmic scale? Nearest greater or nearest smaller?

>java A
hi
0 ==> 1
1 ==> 10
2 ==> 10
9 ==> 10
10 ==> 100
11 ==> 100
99 ==> 100
100 ==> 1000
101 ==> 1000
12345678 ==> 100000000
123456789012345678 ==> 1000000000000000000
1234567890123456789 ==> -8446744073709551616


来源:https://stackoverflow.com/questions/22491505/how-to-round-down-to-the-nearest-power-of-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!