简体   繁体   English

如何在Java中将整数转换为float?

[英]How can I convert integer into float in Java?

I have two integers x and y . 我有两个整数xy I need to calculate x/y and as outcome I would like to get float. 我需要计算x/y ,结果我想浮动。 For example as an outcome of 3/2 I would like to have 1.5. 例如,作为3/2的结果,我希望有1.5。 I thought that easiest (or the only) way to do it is to convert x and y into float type. 我认为最简单(或唯一)的方法是将xy转换为float类型。 Unfortunately, I cannot find an easy way to do it. 不幸的是,我找不到一个简单的方法来做到这一点。 Could you please help me with that? 你能帮帮我吗?

You just need to cast at least one of the operands to a float: 你只需要转换操作数为浮点的至少一个:

float z = (float) x / y;

or 要么

float z = x / (float) y;

or (unnecessary) 或(不必要的)

float z = (float) x / (float) y;

在进入进一步的计算之前,您只需要将第一个值传递给float:

float z = x * 1.0 / y;

You shouldn't use float unless you have to. 除非必须,否则不应使用浮动。 In 99% of cases, double is a better choice. 在99%的情况下,双倍是更好的选择。

int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);

prints 版画

f= 111111.12
d= 111111.1111

Following @Matt's comment. 关注@Matt的评论。

float has very little precision (6-7 digits) and shows significant rounding error fairly easily. float具有非常小的精度(6-7位)并且相当容易地显示出明显的舍入误差。 double has another 9 digits of accuracy. double有另外9位精度。 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. 在99%的情况下使用double而不是float的成本是名义上的,但是由于舍入误差导致的细微错误的成本要高得多。 For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal. 出于这个原因,许多开发人员建议不要使用浮点,强烈推荐BigDecimal。

However I find that double can be used in most cases provided sensible rounding is used . 但是我发现在大多数情况下可以使用double,只要使用合理的舍入

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. 在这种情况下,int x具有32位精度,而float具有24位精度,即使除以1也可能具有舍入误差。 double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result. 另一方面,double具有53位精度,足以获得相当准确的结果。

// The integer I want to convert //我要转换的整数

int myInt = 100;

// Casting of integer to float //将整数转换为float

float newFloat = (float) myInt

Here is how you can do it : 以下是如何做到这一点:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int x = 3;
    int y = 2;
    Float fX = new Float(x);
    float res = fX.floatValue()/y;
    System.out.println("res = "+res);
}

See you ! 再见 !

Sameer: 萨米尔:

float l = new Float(x/y)

will not work, as it will compute integer division of x and y first, then construct a float from it. 将无法工作,因为它将首先计算x和y的整数除法,然后从中构造一个浮点数。

float result = (float) x / (float) y;

Is semantically the best candidate. 在语义上是最好的候选人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM