对 double 进行舍入以将其转换为 int (java)
现在我正在尝试这个:
int a = round(n);
其中 n
是一个 double
但它不起作用。我做错了什么?
Right now I'm trying this:
int a = round(n);
where n
is a double
but it's not working. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
代码片段中
round()
方法的返回类型是什么?如果这是 Math.round() 方法,则当输入参数为 Double 时,它会返回 Long。
因此,您必须转换返回值:
What is the return type of the
round()
method in the snippet?If this is the
Math.round()
method, it returns a Long when the input param is Double.So, you will have to cast the return value:
如果您不喜欢 Math.round() 您也可以使用这个简单的方法:
If you don't like Math.round() you can use this simple approach as well:
将双精度舍入为“最接近的”整数,如下所示:
1.4 -> 1
1.6 -> 2
-2.1 -> -2
-1.3 -> -1
-1.5 -> -2
您可以根据需要更改条件(结果<0.5)。
Rounding double to the "nearest" integer like this:
1.4 -> 1
1.6 -> 2
-2.1 -> -2
-1.3 -> -1
-1.5 -> -2
You can change condition (result<0.5) as you prefer.
Math.round函数重载
当它收到一个 float 值时,它会给你一个 int 值。例如,这会起作用。
当它收到一个 double 值时,它会给你一个 long 值,因此你必须将其类型转换为 int 。
这样做是为了防止精度损失。您的 double 值是 64 位,但是您的 int 变量只能存储 32 位,因此它只是将其转换为 long,即 64 位,但您可以如上所述将其类型转换为 32 位。
The Math.round function is overloaded
When it receives a float value, it will give you an int. For example this would work.
When it receives a double value, it will give you a long, therefore you have to typecast it to int.
This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.
Math.round 的文档说:
无需转换为
int
。也许与过去相比有所改变。Documentation of
Math.round
says:No need to cast to
int
. Maybe it was changed from the past.您确实需要发布一个更完整的示例,以便我们可以看到您想要做什么。从您发布的内容中,我可以看到以下内容。首先,没有内置的 round() 方法。您需要调用
Math.round(n)
,或者静态导入Math.round
,然后像您一样调用它。You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in
round()
method. You need to either callMath.round(n)
, or statically importMath.round
, and then call it like you have.