Convert float to short in Java
In this Java core tutorial, we learn how to convert float value into short value in Java via different solutions.
How to cast float to short value in Java
ConvertFloatToShortExample1.java
public class ConvertFloatToShortExample1 {
public static void main(String[] args) {
float value1 = 12.34F;
short value2 = (short)value1;
System.out.println("float value: " + value1);
System.out.println("short value: " + value2);
}
}
float value: 12.34
short value: 12
Using Float.shortValue() method to get short value from a Float object
ConvertFloatToShortExample2.java
public class ConvertFloatToShortExample2 {
public static void main(String[] args) {
Float value1 = Float.valueOf(34.56F);
short value2 = value1.shortValue();
System.out.println("float value: " + value1);
System.out.println("short value: " + value2);
}
}
float value: 34.56
short value: 34
Happy Coding 😊