java - 四舍五入到最接近的好数字

标签 java rounding

我正在编写一个应用程序,它需要将标签四舍五入到最接近的“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/

相关文章:

java - 覆盖 toString 时遇到问题

java - 是否应该使用自定义 SecurityManager 来对 javax.script.ScriptEngine 进行沙盒处理?

java - 在 Java 中读取二进制文件

java - 我怎样才能在当前过滤器中获取请求的servlet?

java - JVM跳转指令的偏移量怎么会是32768呢?

c++ - 它是如何管理 "rounding"的,因为除法(而不是倍数)在由于四舍五入而截断后返回相同的数量而没有任何损失?

java - 使用 BigDecimal 舍入?

c# - 为什么 C# 会这样舍入?

assembly - x87 可以对 UNsigned QUADword 整数执行精确除法吗?

javascript - 在 JS 中四舍五入到最接近的倍数