You could do:
JOptionPane.showMessageDialog(null, String.format("Your monthly payment is $%.2f", totalCost));
Pregunta
I am very new to Java and playing with displaying a message with GUI. So if use the console
System.out.printf("Your total montly bill is $%.2f", totalCost);
gives me the output with decimal the way it should. I am trying to do the same thing with this, but I get more digits after the decimal because totalCost is a type double. How can I format the output to only show two digits after the decimal? Thanks.
JOptionPane.showMessageDialog(null, "Your monthly payment is " + totalCost);
Solución
You could do:
JOptionPane.showMessageDialog(null, String.format("Your monthly payment is $%.2f", totalCost));
Otros consejos
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
JOptionPane.showMessageDialog(null, "Your monthly payment is " + df.format(d));
System.out.println(df.format(d));
You can also do: JOptionPane.showMessageDialog(this, "Your monthly payment is " + totalCost);
DecimalFormat df = new DecimalFormat("#.##");
String hour = JOptionPane.showInputDialog("Please input your hourly salary: ");
double hr = Double.parseDouble(hour);
double dr = hr * 8;
double wr = hr * 40;
double mr = hr * 160;
double yr = mr * 12;
JOptionPane.showMessageDialog(null, "Yearly: " + df.format(yr) + " / " + "Monthly: "
+ df.format(mr) + " / " + "Weekly: "+ df.format(wr) + " / " + "Hour: " + df.format(hr),
"Yearly Salary Calculator by the hour", JOptionPane.OK_OPTION, icon);