d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Java Printf 2 Decimal Places > Need Help Please
Add Reply New Topic New Poll
Member
Posts: 17,597
Joined: Mar 13 2009
Gold: 0.00
Aug 31 2015 06:47am
I need to write a Java program that prints the base and height of a triangle in a long string to two decimal places.

The program should look like this:

java Main
triangle 1 2
(base = 1.00, height = 2.00) = 1.00

However right now it prints
java Main
triangle 1 2
(base = 1.0, height = 2.0) = 1.00

Using printf, how would I get the base and height to output to 2 decimal places?

Here is my code so far, saved to two different files

Code
import java.util.Scanner;

public class Main {

public static void main (String[] args) {

double base;
double height;
Scanner sc = new Scanner(System.in);
String tri = sc.next();

if (tri .equals("triangle")) {
base = sc.nextDouble();
height = sc.nextDouble();
Triangle triangle = new Triangle(base, height);
System.out.printf(" %s %.2f\n", triangle.toString(), triangle.area());
}
}

}


Code
public class Triangle {

private double base;
private double height;

public Triangle (double basea, double heighta) {
base = basea;
height = heighta;
}

public String toString() {
String toString = "(base = "+base+", height = "+height+") = ";
return toString;
}

public double area() {
double area = (base*height)/2;
return area;
}

}

Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
Aug 31 2015 07:14am
use DecimalFormat("#.##")


Code
DecimalFormat decimalFormat = new DecimalFormat( "#.##" );

public String toString( ) {
String toString = "(base = " + decimalFormat.format( base ) + ", height = "
+ decimalFormat.format( height ) + ") = ";
return toString;
}


don't use printf(%.2f) for printing strings

This post was edited by labatymo on Aug 31 2015 07:18am
Member
Posts: 5,167
Joined: Nov 23 2006
Gold: 11.01
Aug 31 2015 09:25am
Quote (labatymo @ Aug 31 2015 08:14am)
use DecimalFormat("#.##")


Code
DecimalFormat decimalFormat = new DecimalFormat( "#.##" );

public String toString( ) {
String toString = "(base = " + decimalFormat.format( base ) + ", height = "
+ decimalFormat.format( height ) + ") = ";
return toString;
}


don't use printf(%.2f) for printing strings



Just a suggestion -- but use the @Override annotation before your toString method as well. It's good practice so when people are skimming your code we know what's going on without looking too closely.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll