Decimal hour shows 4 min 60 seconds not 5 minutes - swift

I think the title says it all but let me go in to it a bit more.
I am storing decimal hours in a DB every 5 minutes while a user uses my app. I am having a bit of trouble displaying the correct time for some of the 5 min blocks in that it shows 4 min and 60 seconds. Every 3rd 5 min block shows this.
So something like this
4:60
10:00
15:00
19:60
Some even have n:59 instead of n:00
Part of the code is:
let hours = Int(floor(decimalHour))
let mins = Int(floor(decimalHour * 60) % 60)
let secs = Int(floor(decimalHour * 3600) % 60)
Any suggestions what I could be doing wrong?

Binary floating point number can not represent all numbers
exactly, therefore your code is prone to rounding errors.
Example (Swift 2):
let decimalHour = 1.0 + 5.0/60.0
print(decimalHour.debugDescription) // 1.0833333333333333
print(floor(decimalHour * 3600)) // 3899.0
let hours = Int(floor(decimalHour))
let mins = Int(floor(decimalHour * 60) % 60)
let secs = Int(floor(decimalHour * 3600) % 60)
print(hours, mins, secs) // 1 5 59
The actual number stored in decimalHour is slightly less than 1 + 5/60, and therefore the seconds are calculated wrongly.
(Also note that you cannot use % with floating point numbers
in Swift 3, compare What does "% is unavailable: Use truncatingRemainder instead" mean?.)
As already said in the comments, a better approach would be
to store the duration as an integer (number of seconds).
If that is not possible, round the floating point number to
a the number of seconds and then continue with pure integer
arithmetic. Example (works with Swift 2+3):
let decimalHour = 1.0 + 5.0/60.0
let totalSeconds = lrint(decimalHour * 3600) // round to seconds
let hours = totalSeconds / 3600
let mins = (totalSeconds % 3600) / 60
let secs = totalSeconds % 60
print(hours, mins, secs) // 1 5 0

Related

ios game center submit time and show in leader board

in my app i need to submit the time to the game center and i need to show that in Elapsed Time - To the hundredth of a second format.
00:00:00.00
this is the format i want to show in leader board.
In my app im getting the time in following format
ss.SS
ss = seconds
SS = hundredth of a second
i converted the value to double before send it to the game center
double newScoreDouble = [newScore doubleValue];
But when i sending the double score to the game center it asking me to convert it to int64_t format. But when i convert it to that format it loses some part of the double value.
double intPart = 0;
double fractPart = modf(newScoreDouble, &intPart);
int isecs = (int)intPart;
int min = isecs / 60;
int sec = isecs % 60;
int hund = (int) (fractPart * 100);
int64_t time_to_send_through_game_center = min*6000 + (sec*100 + hund);
this is the way i convert double to int64_t
Can any one say how to send whole double value to the game center and display it in Elapsed Time - To the hundredth of a second format.
Thanks
I've done this before. When you're recording a score in the to the hundredth of a second format. You would multiply your seconds with a hundred before submitting.
So let's say the user scored 1minute 44 seconds 300 milliseconds : 1:44:30 = 104.3 seconds. Then you would set your value property of GKScore object equal to 104.3 * 100 = 10430 ,and submit it like that.
Give it a try :)

iPhone: Issue when adding 60 days from the current date in milliseconds

I am trying to add 60 days from the current date in milliseconds. I tried the below code, i'm able to get the current date milliseconds properly, but after adding 60 days milliseconds to current date, its not giving me the expected milliseconds. Please help on correcting what i'm doing wrong here.
double currDateInMilliSecs = [NSDate timeIntervalSinceReferenceDate] * 1000;
NSLog(#"currDateInMilliSecs: %f", currDateInMilliSecs);
double sixtydaysvalue = 60 * 24 * 3600 * 1000;
NSLog(#"sixtydaysvalue: %f", sixtydaysvalue);
double sixtyDaysMilliSecsFromCurrDate = currDateInMilliSecs + sixtydaysvalue;
NSLog(#"sixtyDaysMilliSecsFromCurrDate: %f", sixtyDaysMilliSecsFromCurrDate);
Thank you.
Try
double sixtydaysvalue = 60.0 * 24.0 * 3600.0 * 1000.0;
The value exceeds the max 32-bit int, so you need to perform the calculation in the double type.
You wil try this
NSTimeInterval sixtydaysvalue = 60 * 24 * 3600 * 1000.0

Calculate Pace To String

I am trying to calculate pace (min/mi) and format it as mmmm:ss.
So far I calculate my pace into a float by taking 60 and dividing it by my average speed. At an average speed of 76mph, my average pace is displayed as 0.79. I want to format it so that it converts my 0.79 minutes to mmmm:ss (thus showing my average pace as 0000:47). How can I do this?
double milesPerHour = 76.0;
int secondsPerMile = (int)round(3600.0 / milesPerHour);
NSString *paceString = [NSString stringWithFormat:#"%04d:%02d", secondsPerMile / 60, secondsPerMile % 60];
Not sure if I get your question right, but this is pretty much just math.
You can get the minutes by rounding your value (0.79 in this case) down and you can get seconds by taking your value, subtracting the minutes from it and multiplying that by 60.
So if you'd need 2.35 minutes for a mile, you'd have 2 minutes and 0.35*60 = 21 seconds.

iPhone : integer overflow in expression

I get integer overflow in expression for NSTimerInterval, which is really a double.
NSTimerInterval paymentTermsInMilliSeconds = 30 * 24 * 60 * 60 * 1000;
What's the best way to handle timer interval in iPhone?
This is most likely caused because the calculation is being performed on integers, which is giving an integer result. Try instead to use double values.
EDIT: I just checked, and this is exactly what is happening. If you change your calculation to: NSTimeInterval paymentTermsInMilliSeconds = 30.0 * 24.0 * 60.0 * 60.0 * 1000.0;, then the code gives the correct value of "2592000000". Otherwise, you end up with an overflow and a result of "-1702967296".
You probably mean NSTimeInterval. This is usually a time interval in seconds. To use with milliseconds use 0.001 seconds for milliseconds.
Use,
NSTimerInterval paymentTermsInMilliSeconds = 30 * 24 * 60 * 60 * 1000.0;
Hope, will solve the problem.

% operator for time calculation

I am trying to display minutes and seconds based on a number of seconds.
I have:
float seconds = 200;
float mins = seconds / 60.0;
float sec = mins % 60.0;
[timeIndexLabel setText:[NSString stringWithFormat:#"%.2f , %.2f", mins,seconds]];
But I get an error: invalid operands of types 'float' and 'double' to binary 'operator%'
And I don't understand why... Can someone throw me a bone!?
A lot of languages only define the % operator to work on integer operands. Try casting seconds and mins to int before you use % (or just declare them int in the first place). The constant values you use will also need to be int (use 60 instead of 60.0).
As others have pointed out, you should be using integers. However, noone seems to have spotted that the result will be incorrect. Go back and have another look at modulo arithmetic, and you'll realize you should be doing
int seconds = 200;
int mins = seconds / 60;
int sec = seconds % 60;
Note the last line, seconds % 60 rather than mins % 60 (which will return the remainder of the minutes divided by 60, which is the number of minutes to the hour, and completely unrelated to this calculation).
EDIT
doh, forgot the ints... :)
The 60.0 forces a conversion to double
try:
float seconds = 200;
float mins = seconds / 60;
float sec = mins % 60;
Use ints instead. At least in your example, seems like they're enough (it will also be faster and clearer).
Also, in this case you would get 3.3333... mins, and not 3 minutes as expected. You could use Math.ceil(x) if you need to work with floats.
Do like this:
float seconds = 200.5;
float mins = floor(seconds / 60.0);
float sec = seconds - mins * 60.0;