我正在编写一个应用程序,它需要将标签四舍五入到最接近的“nice”数字。我将在下面放一些代码来演示这一点,但我的问题是我使用了一系列 else ifs 来找到这个数字,但我不能确定上限,所以这不是一个好的策略。是否有任何已知的算法或资源可以帮助我?
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...
最佳答案
您可以使用 Math.log10
在执行“nice number”搜索之前对所有值进行归一化,如下所示:
[编辑] 我刚刚意识到您使用的是 Java 而不是 C#,所以我稍微修改了代码。我周围没有编译器来测试它,但无论如何您应该了解总体思路:
static double getNicerNumber(double val)
{
// get the first larger power of 10
var nice = Math.pow(10, Math.ceiling(Math.log10(val)));
// scale the power to a "nice enough" value
if (val < 0.25 * nice)
nice = 0.25 * nice;
else if (val < 0.5 * nice)
nice = 0.5 * nice;
return nice;
}
// test program:
static void main(string[] args)
{
double[] values =
{
0.1, 0.2, 0.7,
1, 2, 9,
25, 58, 99,
158, 267, 832
};
for (var val : values)
System.out.printf("$%.2f --> $%.2f%n", val, getNicerNumber(val));
}
这将打印如下内容:
0,1 --> 0,1 0,2 --> 0,25 0,7 --> 1 1 --> 1 2 --> 2,5 9 --> 10 25 --> 50 58 --> 100 99 --> 100 158 --> 250 267 --> 500 832 --> 1000
关于java - 四舍五入到最接近的好数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7725278/