我正在编写一个应用程序,它需要将标签四舍五入到最接近的“好”数字。我将在下面放一些代码来演示这一点,但我的问题是,我使用了一系列的else I来找到这个数字,但我不能确定上限,所以这不是一个好策略。是否有任何已知的算法或资源可以帮助我?
if (diff <= 1) {
roundAmount = 0.2;
} else if (diff <= 5) {
roundAmount = 1;
} else if (diff <= 10) {
roundAmount = 2;
} else if (diff <= 25) {
roundAmount = 5;
} else if (diff <= 50) {
roundAmount = 10;
} else if (diff <= 100) {
roundAmount = 20;
} else if (diff <= 250) {
roundAmount = 50;
} else if (diff <= 500) {
roundAmount = 100;
} else if (diff <= 1000){
roundAmount = 200;
} etc...发布于 2012-01-28 07:43:38
与Groo的方法相比,我更喜欢下面的方法,因为它接近267到275,而不是500。它基本上四舍五入到第一位数字,然后是10次方的最接近的四分之一分数。
static double round_pretty(double val) {
var fraction = 1;
var log = Math.floor(Math.log10(val));
// This keeps from adding digits after the decimal
if(log > 1) {
fraction = 4;
}
return Math.round(val * fraction * Math.pow(10, -log))
/ fraction / Math.pow(10, -log);
}输出如下:
0.01 -> 0.01
0.025 -> 0.03 (Groo's does 0.025)
0.1 -> 0.1
0.2 -> 0.2 (Groo's does 0.25)
0.49 -> 0.5
0.5 -> 0.5 (Groo's does 1)
0.51 -> 0.5 (Groo's does 1)
0.7 -> 0.7 (Groo's does 1)
1 -> 1
2 -> 2 (Groo's does 2.5)
9 -> 9
23.07 -> 20
25 -> 30
49 -> 50
50 -> 50 (Groo's does 100 here)
58 -> 60
94 -> 90
95 -> 100
99 -> 100
100 -> 100
109 -> 100 (Groo's does 250 here)
158 -> 150
249 -> 250
267 -> 275
832 -> 825
1234567 -> 1250000
1499999 -> 1500000
1625000 -> 1750000发布于 2011-10-11 19:49:50
我想出了一个非常粗糙的解决方案,它为我刚才测试的所有案例返回正确的值:
public static double foo(long value) {
for (double i = 0.2; true; i *= 5) {
if (i >= value) {
return i / 5;
}
}
}尽管我必须承认Groo发布的数学解决方案会更漂亮。;)
https://stackoverflow.com/questions/7725278
复制相似问题