How can I get my Java code to print out 2 decimal places instead of 1? I can att
ID: 3681610 • Letter: H
Question
How can I get my Java code to print out 2 decimal places instead of 1? I can attach my code if necessary. I have a program that collects a peron's name, id number, how much they make an hour, and how long they worked. The system then prints out their information as:
first and last name, employee id ####, made $###.## in gross pay.
I have everything working but when it prints out that information it uses only 1 decimal place.
part of my code:
// this is my function to calculate the amount of money made.
public double grossPay()
{
return hours * rate;
}
**********************************************************************
then in the main method I declared all my other variables including:
double grossPay;
after declaring my variables, I have the system ask the user for their input.
and this is what I have for it to display back to the user:
System.out.println(pay.getName() + ", Employee Number: " + pay.getIdNumbers() +
", made $" + pay.grossPay() + " in gross pay.");
* How can I get the pay.grossPay() to display in 2 decimal places?
the question states to use text forming so that the gross pay is rounded to two decimal places.
Explanation / Answer
Hi, Please find the below updated statement for your requirement.
Two ways we can do this.
Option 1: By using Syste,.format method.
System.out.println(pay.getName() + ", Employee Number: " + pay.getIdNumbers() +
", made $" +String.format("%.2f", pay.grossPay()) + " in gross pay.");
Option 2: By using DecimalFormat
public double grossPay()
{
DecimalFormat df = new DecimalFormat("#.##");
return Double.valueOf(df.format(hours * rate));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.