简体   繁体   中英

How can I update my Java program to only show two decimal places

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();
 }

}

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);

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);

If you dont want to import anything: String.format

Usage example:

String.format("%.2f", number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM