0

I tried doing this

import java.util.Arrays;
public class Array1
{
   public static void main (String args [])
   {
       double [] a1 = {1.3,2.4,5.6,7.8,9.2};
       double [] a2 = {1.0,3.4,4.2,5.3,6.7};

       double [] a3 = new double[a1.length];
       for(int i = 0; i<a3.length;i++)
       {
           a3[i] = a1[i] - a2[i];
           System.out.print("\n"+a3[i]);
        }

    }
}

However, when it prints, it doesn't print doubles like 1.0. It prints doubles like 0.30000000004. How may I fix this?

1 Answers1

1

You can do it using String.format("%.1f", a3[i]), here by placing count after . you can decide the how many digits you want to show.

       double [] a1 = {1.3,2.4,5.6,7.8,9.2};
       double [] a2 = {1.0,3.4,4.2,5.3,6.7};

       double [] a3 = new double[a1.length];
       for(int i = 0; i<a3.length;i++)
       {
           a3[i] = a1[i] - a2[i];
           String formatted = String.format("%.1f", a3[i]);
           System.out.println(formatted);
       }
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15