在java中将double转换为integer [英] converting double to integer in java

查看:940
本文介绍了在java中将double转换为integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我想将double转换为整数,我知道如果你这样做:

  double x = 1.5; 
int y =(int)x;

你得到y = 1。如果你这样做:

  int y =(int)Math.round(x); 

你可能会得到2.但是,我想知道:由于整数的双重表示有时看起来像1.9999999998或某事,是否有可能通过Math.round()创建的双引号仍然会导致截断的数字,而不是我们正在寻找的舍入数(即:代表代码中的1而不是2)



(是的,我的意思是这样:x的任何值,其中y将显示一个结果截断而不是x的四舍五入表示?)



如果是的话:有没有更好的方法来使一个圆括号的double,而不会产生截断的风险? p>




图形的东西:Math.round(x)返回一个长而不是一个double。因此:Math.round()返回一个看起来像3.9999998的数字是不可能的。因此,int(Math.round())永远不需要截断任何东西,并且将始终工作。

解决方案


有可能通过 Math.round()创建的双引号仍然会导致截断的数字




不, round()将永远舍入你的双倍到正确的值,然后,它将被转换为 long 将截断任何小数位。但是在四舍五入之后,不会有任何分数部分。



以下是 Math.round(double) : / p>


返回参数最近的长度。结果通过加1/2来舍入为整数,取出结果,并将结果转换为长。换句话说,结果等于表达式的值:

 (long)Math.floor(a + 0.5d )



In Java, I want to convert a double to an integer, I know if you do this:

double x = 1.5;
int y = (int)x;

you get y=1. If you do this:

int y = (int)Math.round(x);

You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?

(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)

If so: Is there a better way to make a double into a rounded int without running the risk of truncation?


Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.

解决方案

is there a possibility that casting a double created via Math.round() will still result in a truncated down number

No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.

Here are the docs from Math.round(double):

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

这篇关于在java中将double转换为integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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