java 整数转为double_关于转换:在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成为一个整数,而不存在截断的风险?

计算出一些东西:math.round(x)返回一个长的,而不是双的。因此:math.round()不可能返回3.999998这样的数字。因此,int(math.round())将不需要截断任何内容,并且始终有效。

round(double)返回一个长的,而不是双的。

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

你将永远在round()双圆,到正确的值,然后,它将被截断到一个铸造long将任意位小数。但rounding后,会有不被任何剩余的部分配件。

这里是来自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)

重要的一点是舍入是在舍入方法中完成的。返回一个长值,该值可以安全地强制转换为int(假定返回值始终在int范围内)。

对。无法想象A/long/to int给出的问题。很明显!应该是这样的:(

虽然由于舍入不会发生截断,但由于double是一个非常大的数字[max double: 1.7976931348623157E308]到int的转换,所以可能无法得到预期的结果,double是一个非常小的数字[max int: 2147483647]。只是要记住一些事情。

在datatype intDouble),你可以使用下面的:

Double double = 5.00;

int integer = double.intValue();

他正在寻找一个四舍五入的值。

Double perValue = 96.57;

int roundVal= (int) Math.round(perValue);

解决我的用途。

double a = 1.450;

String sa = String.valueOf(a);

int lengthUntilPoint = sa.indexOf(".")+1;

int power = sa.length() - lengthUntilPoint;

int ia = (int) (a* Math.pow(10, power));

虽然学习一些字符串操作的基础知识可能会让这段代码很有趣,但实际上它不适合这里。不仅因为时间和记忆的使用,而且它是不正确的。DOCS.Oracle .com /JavaSe/ 8 /DOCS/API/Java/Lang//Helip;如果你看,你会看到一些数字。"Chrter没有分开单位和十分之一,而是最大的和第二个最重要的数字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值