Win a copy of Penetration Testing Basics this week in the Security forum!

# Convert minutes to Hours and minutes

Andraz Poje
Ranch Hand
Posts: 32
Hi. I have this code. This code gives me difference in minutes between two date objects.

How do I convert minutes to Hours and minutes?

I tried this:

I get possible loss of precision.... Hm...

Greg Charles
Sheriff
Posts: 2993
12
The problem is the Math.floor() call. You don't need it. It's meant to cut off the fractional part of a floating point number, but you're feeding it a long (integer).

Joanne Neal
Rancher
Posts: 3742
16
As far as the compiler is concerned, floor returns a double, so by assigning it to a long you are losing the decimal part of the value. In this case it doesn't actually matter because that is what you actually want. You need to tell the compiler that you know this is going to happen and you don't care. To do this, you put an explicit cast in.

Edit - as Greg and Henry pointed out, there is a better way to do this. You should use that and just look on this post as an explanation of the compiler error.

Henry Wong
author
Marshal
Posts: 21709
85
You don't need to call floor(), as by default, long operations automatically round down. The floor() method is for floating point, which is probably where the compiler is complaining.

[EDIT: too slow... ]

Henry

Andraz Poje
Ranch Hand
Posts: 32
Greg Charles wrote:That looks right to me. Loss of precision is something you worry about with floating point arithmetic. With integers, you are either wrong or right.

By the way, you don't need Math.floor. Integer division will always truncate off the fractional part.

I understand. But what can I do to skip possible loss of precision error messages?

Andraz Poje
Ranch Hand
Posts: 32
Henry Wong wrote:You don't need to call floor(), as by default, long operations automatically round down. The floor() method is for floating point, which is probably where the compiler is complaining.

[EDIT: too slow... ]

Henry

I casted it... Resolved. Thanks.

Greg Charles
Sheriff
Posts: 2993
12
Sorry, I posted, then realized the when you said you got "possible loss of precision", you actually meant that was a compiler warning. I tried to quickly amend my response, only to find there had been a flurry of activity around it.

If it's not clear already, just do away with the Math.floor() call. You don't need it. As Joanne pointed out, the "loss" that the compiler complains about is converting a double returned by Math.floor() to a long (integer) without a cast. However, you have no reason to stray into the world of floating point arithmetic at all. Your integer division minute / 60 in math may yield a number with fractions, but in the computer will yield an integer with the fractional part throw away. Sorry for the confusion!