-2

I have array of double in java and I need to convert into array of short. Any idea?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Amanpal Singh
  • 145
  • 1
  • 10

2 Answers2

2
    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?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
0

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.

mhvejs
  • 3
  • 8