'How do I divide with doubles and get decimal answers?

I'm hoping to make into a time format. But at the moment I only get either seconds or whole minutes without remaining seconds.

I also tried removing the format and dividing by 60.0 which worked but I was left with too many figures.

Here's my code:

currentPlaybackLabel.text = [NSString 
stringWithFormat:@"%0.0f", realCurrentPlayback / 60];
durationLabel.text = [NSString stringWithFormat:@"%0.0f", totalDuration /60];

I had declared them as doubles but I switched to floats which improved the accuracy. And using @"%.1f" for my format worked!



Solution 1:[1]

There are a couple of things going on.

  1. you should use @"%.{number of decimal places to round to}f" when converting to a string.

  2. make sure that realCurrentPlayback and total duration aren't being computed as ints. You can do so by casting them as whatever type you want to work with like this (float)realCurrentPlayback or (double)realCurrentPlayback if you need the extra precision

  3. I'd also recommend tacking .0f on the end of your int values just to keep things consistent

So here's the corrected code

currentPlaybackLabel.text = [NSString stringWithFormat:@"%.1f", (float)realCurrentPlayback / 60.0f];
durationLabel.text = [NSString stringWithFormat:@"%.1f", (float)totalDuration /60.0f];

This should set your text to strings rounded to the first decimal place

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1