I am trying to cut the decimal off the output of this small code:

import java.util.Scanner;
public class Distance {
public static void main(String[] args) {

java.util.Scanner in = new java.util.Scanner( System.in );

            double x1 = in.nextDouble();
            double y1 = in.nextDouble();
            double x2 = in.nextDouble();
            double y2 = in.nextDouble();

double X= Math.pow((x2-x1),2);
double Y= Math.pow((y2-y1),2);

double d = Math.sqrt(X + Y);

    System.out.println("Distance is: "+d);  


Lets say output is 5192.237545685454687.
I want the output to be 5192.23...

So how do i cut it off by 2 decimal places?

Edited by <M/>

3 Years
Discussion Span
Last Post by old_apache

Use the printf method of the PrintStream class. For e.g. something like:

double yourNum = 5192.237545685454687;
System.out.printf("%.2f", yourNum); // 5192.24

Notice that it has automatically done the rounding for you (.24 instead of .23). If you need to control the rounding, use the DecimalFormat class.

DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(yourNum)); // 5192.23

Edited by ~s.o.s~

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.