Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird double printing in array [duplicate]

I'm writing a program that prints an array containing the sum of the values of two arrays passed as parameters. It all works fine with the exception of the last double value. I want the last value to print as 3.1. Instead it's printing the following:

[5.9, 11.7, 2.4, 3.0999999999999996]

Not sure how to format to print otherwise as I'm not allowed to use a String to solve it. I'm not having that problem with the other values. Here's my code and thanks for the help!

    import java.util.*;

class Sum
{
    public static void main (String [] args)
    {
        double [] a1 = {4.5, 2.8, 3.4, 0.8};
        double [] a2 = {1.4, 8.9, -1.0, 2.3};

        arraySum (a1, a2);

        System.out.println (Arrays.toString (arraySum (a1, a2)));   
    }

    public static double [] arraySum (double [] x, double [] y)
    {
        int length = 0;
        double [] sum = new double [x.length];
        length = x.length;

            for (int i = 0; i <= length - 1; i++)
            {
                sum[i] = x[i] + y[i];
            }

        return sum;

    }
}
like image 315
srsarkar7 Avatar asked Aug 14 '26 10:08

srsarkar7


1 Answers

You want to use deciaml format

DecimalFormat df=new DecimalFormat("#.#");
String outputString=df.format(sum);
like image 55
Tomas Bisciak Avatar answered Aug 16 '26 02:08

Tomas Bisciak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!