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?

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("#.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(yourNum)); // 5192.23
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.