0

I have a video and I need to get the seconds and milliseconds separated and the milliseconds rounded down to the nearest tenth. If the video duration starts off at 4.333333333333333 secs I use floor(num * 10) / 10 to get it to 4.3. When I try to get the remainder by itself using .truncatingRemainder(dividingBy: 1) and/or modf(num).1 I keep getting 0.2999999999999998 instead of 0.3. Why is this happening?

let mixCompositionDuration = CMTimeGetSeconds(mixComposition.duration)
print("mixCompositionDuration: ", mixCompositionDuration) // 4.333333333333333
            
let dubl = Double(mixCompositionDuration)
print("dubl: ", dubl) // 4.333333333333333
            
let mixCompositionRoundDown = floor(dubl * 10) / 10
print("mixCompositionRoundDown: ", mixCompositionRoundDown)  // 4.3

let remainder = mixCompositionRoundDown.truncatingRemainder(dividingBy: 1)
print("remainder: ", remainder) // 0.2999999999999998

let mod = modf(mixCompositionRoundDown)
print("mod: ", mod) // (4.0, 0.2999999999999998)

let modRemainder = mod.1
print("modRemainder: ", modRemainder) // 0.2999999999999998
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256
  • Are you trying to display the seconds and milliseconds as a string to the user? – Sweeper Feb 13 '21 at 05:32
  • no, l have a timer and I need to use the exact milliseconds to set the timer. For example if the video is 4.3 seconds I need the timer to max out at 4.3 seconds when it starts counting. I set the seconds a **4** but I need to set the milliseconds at **3** or whatever that remainder value is. – Lance Samaria Feb 13 '21 at 05:36
  • 1
    Then 0.2999999999999998 should work. See [is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Sweeper Feb 13 '21 at 05:38
  • Ok, I'm reading it now. My way to set the milliseconds was `milliseconds = Int(remainder * 10)`, the problem was I kept getting 2 instead of 3 – Lance Samaria Feb 13 '21 at 05:41
  • 1
    It seems like you should `round` it before converting to `Int`. By the way, 4.3 seconds is 4 seconds and _300_ milliseconds. – Sweeper Feb 13 '21 at 05:44
  • thanks! using `round` before converting it to an `Int` fixed my issue – Lance Samaria Feb 13 '21 at 06:07

0 Answers0