Kris Schouw
Kris Schouw

Reputation: 451

Why is my Float Variable Holding Whole Numbers?

I've been glancing at this code for a while now, and I can't seem to figure out what the probably simple error is... In short, I have a float variable in Java that seems to only be storing the integer content (whole number) of what the value is actually supposed to be. I had this bit of code working before when I had everything crammed into one function, but after I re-factored the code to use more functions, this error occurred. Here's what I've got thus far:

Java Code

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

It's been a long day, so I'm probably just missing something... But rather than printing out something like 54.27 hours, I'm getting a flat 54 hours. The number formatting worked just fine, before... So I don't know what's up.

Upvotes: 0

Views: 303

Answers (2)

Gandalf
Gandalf

Reputation: 2348

dtEnd.getTime() - dtStart.getTime()) / 3600000

This is a division of a long and int so the result itself will be a long and then be casted to float which then only holds the computed long value. To get a float result cast one of the operands to float first or use float literal like 3600000f instead.

Upvotes: 2

Josh Pordon
Josh Pordon

Reputation: 289

At return (dtEnd.getTime() - dtStart.getTime()) / 3600000; you're dividing by an integer, and making the answer an integer. Change it to 3600000.0 (or 3600000f) and you should be golden.

Upvotes: 4

Related Questions