round to nearest nice number

后端 未结 3 703
闹比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 12:05

    You can use Math.log10 to normalize all values before doing your "nice number" search, something like this:

    [Edit] I just realized you are using Java instead of C#, so I modified the code a bit. I don't have a compiler around to test it, but you should get the general idea anyway:

    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));
    }
    

    This will print something like:

    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

提交回复
热议问题