java - 为什么我的浮点变量保存整数?

标签 java variables floating-point numbers number-formatting

我已经浏览这段代码有一段时间了,我似乎无法弄清楚可能简单的错误是什么......简而言之,我在Java中有一个浮点变量,它似乎只存储该值实际应该是什么的整数内容(整数)。之前,当我将所有内容都塞进一个函数中时,这段代码可以正常工作,但是在我重构代码以使用更多函数后,出现了此错误。这是我到目前为止所得到的:

Java 代码

public class ModifyTimeController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        PopulateTimeIntervals(request.getWriter());
    }
    protected void PopulateTimeIntervals(PrintWriter writer) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setMaximumFractionDigits(2);
        float workHours = (float)0.00;

        ...
        /* Code that queries a database for TimeIntervals */
        ...

        while(resultSet.next()) {
            // I was told that this type of conversion is
            // possible since Timestamp is an extension of Date
            Date dtStart = resultSet.getTimestamp("dtStart");
            Date dtEnd = resultSet.getTimestamp("dtEnd");

            // Accumulates the hours worked in each time interval
            workHours += CalculateWorkHours(dtStart, dtEnd);
        }
        // Should print out something like: 54.27
        writer.println(numberFormat.format(workHours).toString());
    }

    protected float CalculateWorkHours(Date dtStart, Date dtEnd) {
        // Divides the difference of the start and end times 
        // (in miliseconds) by 3600000 to convert to hours
        return (dtEnd.getTime() - dtStart.getTime()) / 3600000;
    }
}

这是漫长的一天,所以我可能只是错过了一些东西......但是我没有打印出诸如 54.27 小时之类的内容,而是得到了一个平坦的54 小时。数字格式以前工作得很好...所以我不知道发生了什么。

最佳答案

return (dtEnd.getTime() - dtStart.getTime())/3600000; 处,您除以一个整数,并使结果成为一个整数。将其更改为 3600000.0(或 3600000f),您应该会很满意。

关于java - 为什么我的浮点变量保存整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7521145/

相关文章:

python - 修改 Python 函数中的变量会影响函数外部具有不同名称的变量

sql - mysql变量赋值: how to force assignment order?

r - 接近下溢限制的数字在 tibble 中显示为 `Inf.e-324`?

c++ - 在 C++ 中处理极小的数字

java - Collections.sort() 使我的列表未排序

java - 连接到 LDAPS(Active Directory) 时发生 SSLHandshakeException

variables - 为什么 perl6 不能自动激活,这样我就不必一直使用 "my"?

java - 如何修复 GridBagLayout 按钮大小

java - 使用 For 循环程序片段跟踪指针

algorithm - 是否有邻近图算法或数据结构?