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

我有两个整数 xy。我需要计算 x/y,作为结果,我想得到浮动。例如,作为 3/2的一个结果,我希望有1.5。我认为最简单(或唯一)的方法是将 xy转换为 float 类型。不幸的是,我找不到一个简单的方法来做到这一点。你能帮帮我吗?

383125 次浏览

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;

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 !

You shouldn't use float unless you have to. In 99% of cases, double is a better choice.

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.

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.

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.

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

Is semantically the best candidate.

You just need to transfer the first value to float, before it gets involved in further computations:

float z = x * 1.0 / y;

// The integer I want to convert

int myInt = 100;

// Casting of integer to float

float newFloat = (float) myInt