round to nearest nice number

后端 未结 3 701
闹比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:47

    I prefer the following over Groo's approach, as it rounds 267 to 275 instead of 500. It basically rounds to the first digit, and then the nearest quarter fraction of that power of 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);
    }
    

    The output is as follows:

    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
    

提交回复
热议问题