【问题标题】:Preventing my doubles from rounding up when using yearsTF.setText(String.format("%.0f", years));防止我的双打在使用 yearsTF.setText(String.format("%.0f", years));
【发布时间】:2015-09-26 17:39:55
【问题描述】:

我正在尝试用 Java 尽可能准确地编写这个计算器。它需要几秒钟并将其转换为年,然后分解天、小时、分钟和秒。我已经格式化了我的答案,以便我的 textFields 只显示整数。不幸的是,当我使用 % 来提取余数以转换我的其余变量时,如果我的十分之一是 5 或更多,它会将我的答案向上取整。这是一个GUI,这里是代码。我猜这是一个容忍问题。

private class CalculateButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            double inputSeconds, years, days, hours, minutes, seconds;


            inputSeconds = Double.parseDouble(inputSecondsTF.getText());
            years = inputSeconds / 60 / 60 / 24 / 365;
            days = years % 1 * 365;
            hours = days % 1  * 24;
            minutes = hours % 1 * 60;
            seconds = minutes % 1 * 60;

            yearsTF.setText(String.format("%.0f", years));
            daysTF.setText(String.format("%.0f", days));
            hoursTF.setText(String.format("%.0f", hours));
            minutesTF.setText(String.format("%.0f", minutes));
            secondsTF.setText(String.format("%.0f", seconds));


        }

    }

【问题讨论】:

    标签: java swing formatting


    【解决方案1】:
     yearsTF.setText(String.format("%d", (int)years));
     daysTF.setText(String.format("%d", (int)days));
     hoursTF.setText(String.format("%d", (int)hours));
     minutesTF.setText(String.format("%d", (int)minutes));
     secondsTF.setText(String.format("%d", (int)(seconds+0.5)));
    

    如果您使用这种方法,数字应该向下取整。在设置文本之前,双精度数会转换为整数(例如,4.98 变为 4,4.32 也变为 4)。

    我为秒添加了“+ 0.5”,因为我们希望它被四舍五入。所以,如果我们还剩 58.7 秒,就会发生这种情况: 58.7 + 0.5 = 59.2 -> 转换为 59。

    这也有效:

     yearsTF.setText(String.format("%d", (int)years));
     daysTF.setText(String.format("%d", (int)days));
     hoursTF.setText(String.format("%d", (int)hours));
     minutesTF.setText(String.format("%d", (int)minutes));
     secondsTF.setText(String.format("%.0f", seconds));
    

    【讨论】:

    • 这适用于有余数的数字。但是,当我根据 31,536,000 秒 = 1 年对其进行测试时,它会产生天、小时、分钟和秒的数字。我很好奇。你认为我可以格式化我的双打以使舍入不必要吗?我一直在探索舍入模式和 BigDecimal,但是,我丝毫不知道如何实现它。我这个学期刚开始学习 Java,我认为我的教科书甚至都没有涵盖它。谢谢你,你的意见肯定让我朝着正确的方向前进。
    • 嘿,我更新了我的答案。我认为这种方式更好。
    • 您是否在顶部导入了任何类?我收到本地方法错误。
    • 从头开始!我不小心把小数点留在里面了。谢谢你的帮助!
    猜你喜欢
    • 2013-02-25
    • 2018-07-30
    • 2022-01-03
    • 2011-05-14
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多