Java 在使用yearsTF.setText(String.format(“%.0f”,years))时防止我的双精度整数向上取整;

Java 在使用yearsTF.setText(String.format(“%.0f”,years))时防止我的双精度整数向上取整;,java,swing,formatting,Java,Swing,Formatting,我试图用Java尽可能精确地编程这个计算器。它以秒为单位,将其转换为年,然后分解为天、小时、分钟和秒。我已经格式化了我的答案,所以我的文本字段只显示整数。不幸的是,当我使用%来提取余数来转换其余变量时,如果我的十分之一是5或更多,它会将我的答案取整。这是一个GUI,下面是代码。我猜这是一个宽容的问题 private class CalculateButtonHandler implements ActionListener { public void actionPerf

我试图用Java尽可能精确地编程这个计算器。它以秒为单位,将其转换为年,然后分解为天、小时、分钟和秒。我已经格式化了我的答案,所以我的文本字段只显示整数。不幸的是,当我使用%来提取余数来转换其余变量时,如果我的十分之一是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));


        }

    }
如果使用此方法,数字应向下舍入。double在设置为text'之前被转换为整数(例如,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));

这适用于有余数的数字。然而,当我用31536000秒=1年来测试它时,它将产生-天、小时、分钟和秒的数字。我很好奇。你认为我能把我的双打格式设置成不需要四舍五入吗?我一直在探索舍入模式和BigDecimal,但是,我根本不知道如何实现它。我这学期刚开始学Java,我觉得我的课本甚至没有涵盖它。谢谢你,你的输入肯定让我走上了正确的方向。嘿,我更新了我的答案。我觉得这样比较好。你们有并没有在上面导入任何类?我得到了一个本机方法错误。请擦掉它!我不小心在小数点处离开了。谢谢你的帮助!
 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));