I'm developing a feature that need to format seconds in this form in countdown (begin from 60s):
60.9, 60.8, 60.7,...,59.9, 59.8 etc.
I write this code and is working fine except for 60. When the countdown have 60 sec this print 00.9, 00.8, 00.7, etc. and when goes to 59, work well.
This is the code:
extension RaceTimeFormatterService {
/// This func print like 59.9, 59.8, etc.
func formatForMsTimeElapsed(totalSeconds: Double) -> String {
let (seconds, milliseconds) = divmod(totalSeconds * 1000, 1000)
let (minutes, secondsLeft) = divmod(seconds, 60)
let formatter = DateFormatter()
formatter.dateFormat = "ss.S"
let formattedTime = formatter.string(from: Date(timeIntervalSinceReferenceDate: TimeInterval(minutes * 60 + secondsLeft + milliseconds / 1000)))
return formattedTime
}
}
extension RaceTimeFormatterService {
private func divmod(_ x: Double, _ y: Double) -> (Double, Double) {
return (floor(x / y), x.truncatingRemainder(dividingBy: y))
}
}
Any idea of how to do this in a correct way and don't get 00.9 when seconds is 60 ?
Don't make this about date and time, it's a number so use a NumberFormatter
instead to do the formatting
func formatForMsTimeElapsed(totalSeconds: Double) -> String {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.minimumFractionDigits = 1
//formatter... other configuration like rounding mode if that is relevant
return formatter.string(for: totalSeconds)!
}
Even better is to declare the formatter as a static property outside the function so it doesn't need to be created for each call.