How to convert integer to float in Java?

I have two integers x and y . I need to calculate x/y , and as a result I would like to get a float. For example, as a 3/2 result, I would like to have 1.5. I thought the easiest (or only) way to do this is to convert x and y to float type. Unfortunately, I cannot find an easy way to do this. Could you help me with this?

+50
java floating-point integer
Dec 07 2018-10-14
source share
6 answers

You just need to distinguish at least one of the operands for the float:

 float z = (float) x / y; 

or

 float z = x / (float) y; 

or (optional)

 float z = (float) x / (float) y; 
+100
Dec 07 2018-10-14T00:
source share

You should not use float unless you need to. In 99% of cases, double choice is the best 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 

After the comment by @Matt.

float has very little accuracy (6-7 digits) and a fairly significant rounding error. double has another 9 digits of precision. The cost of using double instead of float is conditional in 99% of cases, but the cost of a subtle error due to rounding errors is much higher. For this reason, many developers recommend not using floating point at all, and highly recommend BigDecimal.

However, I believe that double can be used in most cases , provided that reasonable rounding is used .

In this case, int x has 32-bit precision, while float has 24-bit precision, even dividing by 1 may have a rounding error. double, on the other hand, has 53-bit precision, which is more than enough to get a sufficiently accurate result.

+5
Dec 07 '10 at 15:49
source share

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

 float z = x * 1.0 / y; 
+4
Apr 28 2018-12-12T00: 00Z
source share

Here's 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!

+3
Dec 07 2018-10-14
source share

// The integer I want to convert

 int myInt = 100; 

// Cast an integer to float

 float newFloat = (float) myInt 
+2
Dec 22 '15 at 5:43
source share

Samir:

 float l = new Float(x/y) 

will not work, as it will first compute the integer division of x and y, and then build a float from it.

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

Semantically the best candidate.

+1
Apr 27 2018-12-12T00:
source share



All Articles