I have array of double in java and I need to convert into array of short. Any idea?
2 Answers
double[] d = { 2, 3.2, 4.8, 123456789.123 };
short[] s = new short[d.length];
for (int i = 0; i < d.length; i++) {
s[i] = (short) d[i];
}
System.out.println("short output: " + Arrays.toString(s));
---------------------
Result: short output: [2, 3, 4, -13035]
Is that really what you need? Is the precision loss not important for you?
Comments
How do you want to print it...? You can cast your double to a short when printing a single value from the array like this:
public class array {
public static void main(String[] args){
double [] array = new double[] {132.45612, 9556.456789876, 6513.987652, 123456789.123};
System.out.println((short)array[3]);
}
}
This outputs -13035
By changing the number in the sysout, you should get a different result.
shortvariable can hold. Check stackoverflow.com/q/18860817/10819573 to understand it.