【问题标题】:How can I update my Java program to only show two decimal places如何更新我的 Java 程序以仅显示两位小数
【发布时间】:2014-10-29 02:00:04
【问题描述】:

课堂作业基本上是有一个对话框,询问用户员工姓名、小时工资和一周的小时数。它将其输出到文本文件。我完成了那部分,老师说他发现输出有 4 位小数,例如。 34.5500

我在这里寻求帮助,我如何只能显示两个小数点,所以它是 34.55。这是我编译的代码。

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

}

【问题讨论】:

  • 你可以在NumberFormat做一些研究...

标签: java file-io keyboard decimal rounding


【解决方案1】:

研究使用printf 函数。您可以使用百分比修饰符来填充代码。它支持整数 (%d) 浮点数 (%f) 字符 (%c) 和字符串 (%s)。都可以根据自己的喜好进行格式化。

System.out.printf("%.2f", floatVariable);

【讨论】:

    【解决方案2】:

    如果我理解您的问题,您可以使用NumberFormat.format(double) 喜欢

    NumberFormat fmt = new DecimalFormat("#.##");
    payFile.writeString(name);
    payFile.writeString(fmt.format(pay));
    payFile.writeString(fmt.format(hours));
    

    或者,您可以使用 String.format("%.2f", pay); 之类的东西

    【讨论】:

      【解决方案3】:

      如果你不想导入任何东西:String.format

      使用示例:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2010-11-05
        • 1970-01-01
        • 1970-01-01
        • 2015-05-06
        • 1970-01-01
        • 2013-02-23
        相关资源
        最近更新 更多