How to round double to nearest whole number and then convert to a float?

前端 未结 4 1133
故里飘歌
故里飘歌 2020-12-30 22:43

I am using java.util.Random to generate a random gaussian. I need to convert this gaussian to a float value. However gaussian is a double, so I need some way to either round

4条回答
  •  情话喂你
    2020-12-30 23:14

    For what is worth:

    the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer

    +-------+--------+
    | input | output |
    +-------+--------+
    |     1 |      0 |
    |     2 |      0 |
    |     3 |      5 |
    |     4 |      5 |
    |     5 |      5 |
    |     6 |      5 |
    |     7 |      5 |
    |     8 |     10 |
    |     9 |     10 |
    +-------+--------+
    

    private int roundClosest(final int i, final int k) {
        int deic = (i % k);
        if (deic <= (k / 2.0)) {
            return (int) (Math.floor(i / (double) k) * k);
        } else {
            return (int) (Math.ceil(i / (double) k) * k);
        }
    }
    

提交回复
热议问题