Most of the time, Java developers have to do type conversion. In this example, I will cover the conversion of float datatype to int. There are several ways to achieve this.
Solution 1
public static void main( String[] args ) {
float value = 0.9f;
System.out.println( "0.9f converted to int : " + (int) value );
value = 1.1f;
System.out.println( "1.1f converted to int : " + (int) value );
}
}
Solution 1
public class FloatToIntCasting {
public static void main( String[] args ) {
float value = 0.9f;
System.out.println( "0.9f converted to int : " + (int) value );
value = 1.1f;
System.out.println( "1.1f converted to int : " + (int) value );
}
}
Output
0.9f converted to int : 01.1f converted to int : 1
As we can see in the above example, casting a float to int results in downcasting. It simply removes the fraction part and returns the value.
Solution 2
public class FloatToIntUsingMathRound {
public static void main( String[] args ) {
float value = 0.9f;
System.out.println( "0.9f rounded to int : " + Math.round( value ));
value = 1.49f;
System.out.println( "1.49f rounded to int : " + Math.round( value ));
value = 1.5f;
System.out.println( "1.5f rounded to int : " + Math.round( value ));
}
}
Output :
0.9f rounded to int : 1
1.49f rounded to int : 1
1.5f rounded to int : 2
Math.round rounds the float to the closest int value. It simply looks for the middle half value i.e. 0.5,
- < 0.5 discards the fraction part like 1.49f is rounded to 1
- >= 0.5 moves the value to the next int value like1.5f is rounded to 2
Note that java Math class has two overloaded method
- Math.round(float) returns int
- Math.round(double) returns long
Comments
Post a Comment