如何将double舍入到最接近的整数然后转换为float? [英] How to round double to nearest whole number and then convert to a float?

查看:170
本文介绍了如何将double舍入到最接近的整数然后转换为float?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 then convert it to a float. I need to round to the nearest whole number, rounding up. Here is my question: How?

推荐答案

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

浮动b =(浮动)Math.round(a);

取决于您是指舍入到最接近的整数(圆形)还是向上舍入(ceil)。

Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).

小心将double转换为float的精度损失,但这不应该是一个问题。

Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.

这篇关于如何将double舍入到最接近的整数然后转换为float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆