1

How can I convert my answer from 0.0 to 0.000? Rightnow it jst shows answer 175.0 etc but I would like it to show 175.000

Examples:

175.0 = 175.000
10.0 = 10.000
5.0 = 5.000
etc.

In my example, Code to calculate angle between clock hands:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        int hours = 0;
        int minutes = 0;
        Scanner dis=new Scanner(System.in);
    String line;
    String[] lineVector;
    line = dis.nextLine();
    lineVector = line.split(":");
    hours=Integer.parseInt(lineVector[0]);
    minutes=Integer.parseInt(lineVector[1]);
        if (hours < 0 || minutes < 0 || hours > 24 || minutes > 60) {
            System.out.println("Please enter correct input.");
        } else {
            if (hours == 24)
                hours = 0;
            if ( minutes == 60)
                minutes = 0;

            double hourHandAngle = 0.5 * (hours * 60 + minutes);
            int minuteHandAngle = 6 * minutes;

            double angle = Math.abs(hourHandAngle - minuteHandAngle);
            if (angle > 360){
              angle = angle - 360;
              System.out.println(angle);
              System.exit(0);
            }
            if (angle > 180 || angle <= 360){
              angle = 360 - angle;
              System.out.println(angle);
              System.exit(0);
            }
            System.out.println(angle);
        }
    }
}

It needs to show anwer 0.000 not 0.0 thought.

SOLVED with : System.out.printf("%.3f", angle);

waynekenoff
  • 47
  • 1
  • 6

3 Answers3

1

You can use string formatter to specify decimal places.

%.0f is the format string for a float, with 0 decimal places.

 String.format( "%.3f", value )
Abhilekh Singh
  • 2,845
  • 2
  • 18
  • 24
0

Use MessageFormat, you can format number output as you wish

import java.text.MessageFormat;


public class Test {

    public static void main(String[] args) {

        Object[] params = {123, 1222234.567 };

        String msg = MessageFormat.format("{0,number,percent} and {1,number,,###.###}", params);

        System.out.println(msg);

    }

}
Yu Jiaao
  • 4,444
  • 5
  • 44
  • 57
0

Try using DecimalFormat.

Here is an example:

DecimalFormat format = new DecimalFormat("#.000"); 
System.out.println(format.format(5.0));

For more information look at the comments of this answer.