Search code examples
javaroundingrounding-error

Can't round decimals to 4 decimal points in java for gravity program


So, I'm trying to get the decimals in a table I have for a gravity program that I created to round after 4 decimals. However, whenever I've tried to round it, it either will print the table without rounding, or it will start to print the table, and then throw an error at me. I'm sure what I doing wrong, and I've tried to look online for help, but it hasn't helped. I have a few lines commented out below to show where I have tried to round to 4 decimals places, but hasn't worked. I'll post my code below to see if you guys could please help me figure out what I'm doing wrong.

public class Gravity 
{
    public static void main(String[] args) 
    {
        Gravity g = new Gravity();
        System.out.printf("%5s%20s%20s\n", "Time", "Distance Earth", "Distance Moon");
        // Gravity.format()
    
        // DecimalFormat df = new DecimalFormat("###.####");
        // System.out.println(df.format(g));
      
       for (int i = 1; i <= 10; i++) 
       {
           System.out.printf("%5d%20fm%20fm\n", + i,g.distanceFallen(i, 9.8), g.distanceFallen(i, 1.625));
           // System.out.format("%.4f", i);  
       }
   }

 /* private static Gravity format(String string, int i) 
    {
        // 
        return i;
    }*/

    public double distanceFallen (double time, double gAcc)
    {
        // System.out.format("%.4f");
        // System.out.format("%.4f", time);
        return (0.5)*gAcc*Math.pow(time, 4);
    }
}

EDIT: Also, here's what the table looks like, just to make clear up any potential confusion.

Time      Distance Earth       Distance Moon
   1            4.900000m            0.812500m
   2           78.400000m           13.000000m
   3          396.900000m           65.812500m
   4         1254.400000m          208.000000m
   5         3062.500000m          507.812500m
   6         6350.400000m         1053.000000m
   7        11764.900000m         1950.812500m
   8        20070.400000m         3328.000000m
   9        32148.900000m         5330.812500m
  10        49000.000000m         8125.000000m

Solution

  • Change your formatting to:

    "%5d%20.4fm%20.4fm\n"
    

    You'll want to change your header formatting to 24 instead of 20 too.