-2

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

4
  • You should provide more detail in your question, what problem are you facing, how do you want to handle values that are to large, rounding etc. Commented Feb 17, 2021 at 8:15
  • @JoakimDanielson . I have to play the array using audio track and it accepts short Commented Feb 17, 2021 at 8:24
  • You may get a different value for any number beyond the max and min value a short variable can hold. Check stackoverflow.com/q/18860817/10819573 to understand it. Commented Feb 17, 2021 at 8:37
  • That wasn't much of a clarification. Commented Feb 17, 2021 at 10:06

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.