-3

Can someone please help me with formatting my output? I have tried so many different things and all eclipse keeps giving me is error error error. I am looking to only have a decimal point with 2 numbers after it.

import java.util.Scanner;

public class Radius {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    //Define variables
    double dim;
    final double PI = 3.14159;

    //Prompt for radius
    System.out.printf("Enter the radius: ");
    double num1 = input.nextDouble();

    //Compute diameter and area
   double dim1 = num1 * 2;
   double cir = dim1 * PI;
   double area = num1 * num1 * PI;

    //Print output
   System.out.println("The diameter is " + dim1);
   //System.out.println();
   //System.out.println();
   System.out.println("The circumference is " + cir %2f);
   //System.out.println();
   //System.out.println();
   System.out.println("The area is " + area %2f);
}
}
jake
  • 237
  • 4
  • 13
  • You need to show us what you've tried and what "error error error" actually means. – Jim Garrison Jan 23 '16 at 05:36
  • yes google may times – jake Jan 23 '16 at 05:37
  • How can you claim to have searched? Google "[`java format double`](https://www.google.com/search?q=java+format+double&ie=utf-8&oe=utf-8)", and you'll find many examples of how to do this. Top one right now was "[Double decimal formatting in Java](http://stackoverflow.com/questions/12806278/double-decimal-formatting-in-java)", right here on StackOverflow. – Andreas Jan 23 '16 at 05:51

1 Answers1

1

One way is to use java.lang.String#format - it uses the old C-style format to specify formatting such as the one you desire.

The following should work:

System.out.println(String.format("The diameter is %.2f", dim1))

The same applies for the other two output lines. Additional formatting can be used - details are found in the Java API docs:

String#format format specification

EDIT: The 'simplest' way is as per Andreas' comment below, but the same principle applies

Mr Rho
  • 578
  • 3
  • 16