java整数转浮点数_当存储在浮点中时,Java如何舍入整数

how do floating point numbers round when they are made in java?

当您使用构造(int)d时,Java会截断(四舍五入为零),其中d的类型为double或float.如果需要舍入到最接近的整数,可以使用下面的行:

int a = (int) Math.round(d);

the classic example is 0.1 what is often quoted as rounding to 0.0999999999998 (or something like that).

您提到的问题并不存在,整数可以精确地表示为double(对于-253和253之间的整数).如果您要舍入的数字来自应该产生整数但由于浮点舍入错误而可能没有的先前计算,则(int)Math.round(d)可能是您应该使用的解决方案.这意味着只要累积误差不超过0.5,您将获得正确的整数.

your legacy code uses a floating point when it should really be using n integer. But, its to expensive to change every instance of that variable (or several) in the code.

如果产生double d的计算仅是-,*和其他整数的计算,并且产生介于-253和253之间的中间结果,则d自动包含一个整数(这是精确的,因为涉及的浮点计算是精确的,并且整数,因为精确结果是整数),您可以使用更简单的(int)d进行转换.另一方面,如果涉及除法运算符或非整数操作数,则不要轻易更改d的类型,因为它会更改这些计算的结果.

Also is the behavior different when calling Float.parseFloat(String) when the String is an integer like "1234567890"?

这将产生一个浮点数,其值是有理数1234567890中最接近的可表示单精度值.恰好是1234567936.0f.

And is the behavior also the same when String is a Floating point with more precision than the Float can store.

从技术上讲,“ 0.1”比Float可以存储的精度更高.同样,从技术上讲,前面的示例1234567890也比Float可以存储的精度更高.行为是相同的:Float.parseFloat(“ 0.1”)产生最接近有理数0.1的浮点数.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值