如何舍入到最接近的10或100或x

时间:2016-09-08 16:50:20

标签: java rounding

How to round up to the nearest 10 (or 100 or X)?

这个链接为r中的问题提供了解决方案,我们怎样才能在java中实现类似的东西?

这不是简单舍入的情况,而是根据值本身进行的复杂舍入,例如: 0.0322到0.04, 3.22至4, 32.2至40, 42.2至50和 422.2至500。

2 个答案:

答案 0 :(得分:1)

我想不出有多少原因导致这个问题被低估了,特别是因为没有说“X”必须是10的效力。

如果你的“X”意味着10的效力,你可能会发现 枚举RoundingMode和MathContext和BigDecimal类很有帮助。 详情请见 https://docs.oracle.com/javase/8/docs/api/

反正: 这个Java方法处理任何舍入更大的一个更新的int:

int round(int num, 
          int base /* "X", MUST be greater than 1 */, 
          boolean roundMiddleUp /* true is usual in business calculations */) {
    int lower = (num / base) * base - (num < 0 ? base: 0);
    int upper = lower + base;

    int difLower = Math.abs(num - lower);
    int difUpper = Math.abs(num - upper);
    int rounded = (difLower < difUpper) ? lower : (difLower != difUpper) ? upper : roundMiddleUp ? upper : lower;
    return rounded;
}

希望它有所帮助。

答案 1 :(得分:1)

请尝试此公式

class Main { public static void niceround(double x) { System.out.println(x+" to " + Math.ceil(x * Math.pow(10, -Math.floor(Math.log10(x)))) / Math.pow(10, -Math.floor(Math.log10(x)))); } public static void main(String[] args) { niceround(0.0322); niceround(3.22); niceround(32.2); niceround(42.2); niceround(422.2); } } 您可以尝试此公式online

/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:36808,suspend=y,server=n -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/charsets.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/icedtea-sound.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/jce.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/jsse.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/management-agent.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/resources.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/rt.jar:/home/dac/proj/javatest2016/out/production/javatest2016:/home/dac/Downloads/idea-IU-145.972.3/lib/idea_rt.jar Main
Connected to the target VM, address: '127.0.0.1:36808', transport: 'socket'
0.0322 to 0.04
3.22 to 4.0
32.2 to 40.0
42.2 to 50.0
422.2 to 500.0
Disconnected from the target VM, address: '127.0.0.1:36808', transport: 'socket'

Process finished with exit code 0

测试

$sql ="select * from products where 1";
if($filter['color'])
   $sql.="and color='$color'";
if($filter['manufracture'])
   $sql.="and color='$manufracture'";
....
and lastly execute the query.