Java – Convert Int to Float

In this tutorial, we shall learn how to convert an integer value to a float value.

Firstly, we shall go through the process of widening casting, where we shall take the advantage of implicit casting of lower datatype to higher datatypes.

Secondly, we shall discuss about Float.intBitsToFloat() method, which converts the representation of integer bits to float bits.

Also, there is a third method of using Integer.floatValue(). This is kind of a wrapper to the first process. But anyway, we shall go through an example using Integer.floatValue() method.

1. Convert int to float using Widening Primitive Conversion

Int is a smaller datatype and float is a larger datatype. So, when you assign an int value to float variable, the conversion of int to float automatically happens in Java. This is also called widening casting or widening primitive conversion.

So, to convert an in to float using widening casting, you can just assign a value of int to float.

In the following example, we have a variable i which is of int type. We shall assign i to float variable f during its declaration.

Java Program

</>
Copy
/**
 * Java Program - Convert Int to Float
 */

public class IntToFloat {

	public static void main(String[] args) {
		int i = 125;
		float f = i;
		System.out.println(f);
	}
	
}

Output

125.0

2. Convert int to float using Float.intBitsToFloat()

Integer has a size of 4 bytes and float has a size of 4 bytes. Java allows you to convert this integer representation of 4 bytes into float representation using static method intBitsToFloat() of Float class.

In the following example, we shall take an integer variable initialized to a hexadecimal representation of 4 bytes. Pass this integer variable as argument to intBitsToFloat() method.

Java Program

</>
Copy
/**
 * Java Program - Convert Int to Float
 */

public class IntToFloat {

	public static void main(String[] args) {
		int i = 0x40000085;
		float f = Float.intBitsToFloat(i);
		System.out.println(f);
	}
	
}

Output

2.0000317

3. Convert int to float using Integer.floatValue() method

Integer.floatValue() performs a widening primitive conversion on this integer object and returns a float value.

In the following example, we shall take an integer object initialized to a value, and call floatValue() method on this object.

Java Program

</>
Copy
/**
 * Java Program - Convert Int to Float
 */

public class IntToFloat {

	public static void main(String[] args) {
		Integer i = 85;
		float f = i.floatValue();
		System.out.println(f);
	}
	
}

Output

85.0

Conclusion

In this Java Tutorial, we learned how to write Java programs to convert an Int to Float, with the help of example Java programs.