Reputation: 65
The class assignment is basically to have a dialog box that asks the user for employee name, hourly pay, and hours for the week. It outputs it to a text file. I completed that part and the teacher said he was find that the output had 4 decimal places, ex. 34.5500
I'm here to ask for assistance on how I can only show two decimal spots so its 34.55. Here is the code I complied.
package out.put.of.a.file;
import javax.swing.JOptionPane;
public class OutPutOfAFile
{
public static void main(String[] args)
{
OutputFile payFile;
payFile = new OutputFile("payroll.txt");
String name;
Double pay, hours;
String answer;
Keyboard k;
k = new Keyboard();
do
{
name = JOptionPane.showInputDialog("Enter the employee's name:");
pay = Double.parseDouble(JOptionPane.showInputDialog("Enter the employee's hourly wage:"));
hours = Double.parseDouble(JOptionPane.showInputDialog("Enter the employee's total hours:"));
payFile.writeString(name);
payFile.writeDouble(pay);
payFile.writeDouble(hours);
payFile.writeEOL();
answer = JOptionPane.showInputDialog("Do you have another employee to enter? (yes/no)");
} while (answer.equalsIgnoreCase("yes"));
payFile.close();
}
}
Upvotes: 0
Views: 80
Reputation: 493
If you dont want to import anything: String.format
Usage example:
String.format("%.2f", number);
Upvotes: 0
Reputation: 201517
If I understand your question you might use a NumberFormat.format(double)
like
NumberFormat fmt = new DecimalFormat("#.##");
payFile.writeString(name);
payFile.writeString(fmt.format(pay));
payFile.writeString(fmt.format(hours));
Alternatively, you could use something like String.format("%.2f", pay);
Upvotes: 0
Reputation: 476
Look into using the printf
function. You can use percent modifiers for padding the code. It supports integers (%d) floats (%f) characters (%c) and strings (%s). All can be formatted to your liking.
System.out.printf("%.2f", floatVariable);
Upvotes: 2