在Java中如何将整数转换为浮点数?
我有两个整数 x 和 y。我需要计算 x/y ,结果我想得到浮动。例如,作为 3/2
的结果,我想要 1.5。我认为最简单(或唯一)的方法是将 x 和 y 转换为 float 类型。不幸的是,我找不到一种简单的方法来做到这一点。你能帮我吗?
I have two integers x
and y
. I need to calculate x/y
and as outcome I would like to get float. For example as an outcome of 3/2
I would like to have 1.5. I thought that easiest (or the only) way to do it is to convert x
and y
into float type. Unfortunately, I cannot find an easy way to do it. Could you please help me with that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您只需将至少一个操作数强制转换为浮点数:
or
or(不必要)
You just need to cast at least one of the operands to a float:
or
or (unnecessary)
// 我想要转换的整数
// 将整数转换为浮点数
// The integer I want to convert
// Casting of integer to float
除非必要,否则不应使用浮动。在 99% 的情况下,双倍是更好的选择。
打印
以下 @Matt 的评论。
float 的精度非常低(6-7 位),并且很容易显示显着的舍入误差。 double 还有另外 9 位精度。在 99% 的情况下,使用 double 而不是 float 的成本只是名义上的,但由于舍入误差而导致的微妙错误的成本要高得多。因此,许多开发人员建议根本不要使用浮点,并强烈推荐 BigDecimal。
不过,我发现在大多数情况下都可以使用 double 只要使用合理的舍入。
在这种情况下,int x 具有 32 位精度,而 float 具有 24 位精度,即使除以 1 也可能会产生舍入误差。另一方面,double 具有 53 位精度,足以获得相当准确的结果。
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
prints
Following @Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
您只需将第一个值传输为浮点数,然后它就会参与进一步的计算:
You just need to transfer the first value to float, before it gets involved in further computations:
具体方法如下:
再见!
Here is how you can do it :
See you !
Sameer:
不起作用,因为它将首先计算 x 和 y 的整数除法,然后从中构造一个浮点数。
从语义上讲是最好的候选者。
Sameer:
will not work, as it will compute integer division of x and y first, then construct a float from it.
Is semantically the best candidate.