round to nearest nice number

后端 未结 3 702
闹比i
闹比i 2021-02-06 11:05

I\'m writing an application which requires rounding labels to the nearest \'nice\' number. I\'ll put some code below to demonstrate this, but my issue is that I was using a ser

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 11:59

    I came up with this quite crude solution, which returns the correct values for all of the cases I tested just now:

    public static double foo(long value) {
        for (double i = 0.2; true; i *= 5) {
            if (i >= value) {
                return i / 5;
            }
        }
    }
    

    Although I must admit that a mathematical solution as posted by Groo would be more beautiful. ;)

提交回复
热议问题