如何将double舍入到最接近的整数然后转换为float?

我使用java.util.Random生成随机高斯。 我需要将此高斯转换为浮点值。 然而高斯是一个双,所以我需要一些方法来圆或然后将其转换为浮点数。 我需要四舍五入到最近的整数,四舍五入。 这是我的问题:如何?

float b = (float)Math.ceil(a);float b = (float)Math.round(a);

取决于你的意思是“舍入到最接近的整数”(圆形)或“向上圆形”(ceil)。

注意在将double转换为float时精度会降低,但这不应该是一个问题。

这是一个简单的例子:

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

结果和输出将是: 5.0
最接近的上限浮动到起始值double a = 4.56777
在这种情况下,建议使用round,因为它采用double值并提供整个long

问候

Math.round

值得的是:

可以使用Math.ceil或Math.floor计算与任何给定输入最接近的整数,如下表所示,具体取决于输入与下一个整数之间的距离

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