-3

I created a program that calcuates the average acceleration using 3 inputs. Here's my code:

    Scanner input = new Scanner(System.in);

    System.out.print("Enter v0, V1, and t:  ");
    double v0 = input.nextDouble();
    double v1 = input.nextDouble();
    double t = input.nextDouble();

    double acceleration = (v1 - v0) / t;

    System.out.println("The average acceleration is " + acceleration);

Here's the output:

Enter v0, V1, and t: 5.5 50.9 4.5
The average acceleration is 10.088888888888889

Here's the expected output:

Enter v0, V1, and t: 5.5 50.9 4.5
The average acceleration is 10.0889

I'm not quite sure how to trim the excess 8's in my code. I tried casting acceleration into a float and that somewhat works, but there is still too many 8s with it.

1 Answers1

3

You can use decimal format class like this

import java.text.DecimalFormat;

public class Tests {
 public static void main (String args []) {

     double d = 10.088888888888889;

     DecimalFormat decimalFormat = new DecimalFormat("00.0000");

     System.out.println(decimalFormat.format(d));
 }
 }
sol4me
  • 15,233
  • 5
  • 34
  • 34