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

前端 未结 4 1135
故里飘歌
故里飘歌 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:15

    Here is a quick example:

    public class One {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
    
            double a = 4.56777;
            System.out.println( new Float( Math.round(a)) );
    
        }
    
    }
    

    the result and output will be: 5.0
    the closest upper bound Float to the starting value of double a = 4.56777
    in this case the use of round is recommended since it takes in double values and provides whole long values

    Regards

提交回复
热议问题