get string with minutes and seconds from double in swift

To get a string with minutes and seconds from a Double value in Swift, you can calculate the minutes and seconds separately using some basic math operations. Here's a code snippet to achieve this:

main.swift
func formatTimeFromSeconds(totalSeconds: Double) -> String {
    let minutes = Int(totalSeconds) / 60
    let seconds = Int(totalSeconds) % 60

    return String(format: "%02d:%02d", minutes, seconds)
}

let totalTimeInSeconds: Double = 125.5
let formattedTime = formatTimeFromSeconds(totalSeconds: totalTimeInSeconds)
print(formattedTime) // Output: 02:05
357 chars
11 lines

In this code:

  1. We define a formatTimeFromSeconds function that takes a Double representing the total time in seconds.
  2. We calculate the minutes by integer dividing the total seconds by 60.
  3. We calculate the remaining seconds by taking the modulus (%) of total seconds and 60.
  4. We then format the minutes and seconds as a string with leading zeros for display.
  5. Finally, we call the function with a sample totalTimeInSeconds value and print the formatted time.

This function will work for converting a Double value representing total seconds into a string with minutes and seconds in the format "mm:ss".

main.swift
0 chars
1 lines

related categories

gistlibby LogSnag