Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert integer into float in Java?

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?

like image 785
Roman Avatar asked Dec 07 '10 14:12

Roman


People also ask

How do I convert an int to a float in Java?

Use the floatValue() Function to Convert an Integer Into a Float in Java. The floatValue() function can convert a given integer value into float. It belongs to the java. lang.

Can you go from int to float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00. The %.


2 Answers

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; 
like image 194
Matt Ball Avatar answered Oct 06 '22 22:10

Matt Ball


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.

like image 30
Peter Lawrey Avatar answered Oct 06 '22 22:10

Peter Lawrey