Reputation: 181
Background:
I have an array of integer times given as 0830 for 08:30, 1745 for 17:45, etc.
I need to calculate the time difference between times. So I'm first turning integer times into floating point times by dividing by 100.0. This means that 0830 will become 8.30.
int inTime = 0830, outTime = 1745;
float newIntime = inTime/100.0;
float newOutTime = outTime/100.0;
The next step, and this is my question, is: How do I divide the decimal part by 0.6 so I get 8.50. This is the only way I'll be able to subtract/add times and get the correct time difference in a meaningful format.
I have not been able to figure out (or look up) a way to multiply the decimal part, i.e. to "access" only what's on the right side of the decimal point. Any help will be appreciated!
Upvotes: 0
Views: 669
Reputation: 391
It is easier and more reasonable to convert 08:30 to 8.5 rather than 8.3 for floating point calculation. It is 8.5 hours from 0:00. Convert back is also easy. Hour is whatever to the left of decimal point and minute is whatever to the right of decimal point multiple by 60.
Upvotes: 0
Reputation: 5858
You do not want to do this in float, because you will be potentially losing precision.
I would suggest doing something along the line of:
// or use std::tm per Potatoswatter's comment
struct Time
{
int hours;
int minutes;
Time(int time)
{
hours = time/100;
minutes = time-hours*100;
}
};
Time operator-(const Time& a, const Time& b)
{
// You could also just return these minutes and be done with it
int minutes (a.hours-b.hours)*60 + (a.minutes-b.minutes);
Time result;
result.hours = minutes/60;
result.minutes = minutes-result.hours;
}
int main()
{
Time inTime(830), outTime(1745);
Time result = inTime-outTime;
// ...
return 0;
}
Another thing to keep in mind, is that you should not write:
Time inTime(0830);
because the compiler will think that you are talking about octal base (and it cannot have the 8 as a digit).
Upvotes: 0
Reputation: 28882
Extract it with modf. That should eliminate the extra loss of precision.
Upvotes: -1
Reputation: 38683
Don't convert to float in the first place. Use modulus to extract the minutes:
int inTime = 830;
int inHours = inTime / 100;
int inMinutes = inTime % 100;
int inTotalMinutes = inHours * 60 + inMinutes;
Also, 0830
is not a valid literal. The leading zero causes it to be interpreted as an octal number, and 8 is not a valid octal digit.
Upvotes: 2
Reputation: 9400
float intPart = floor(newInTime);
float converted = intPart + (newInTime - intPart) / 0.6;
And it's better to not use float for this purpose. See others' answer.
Upvotes: 2