When I call this method, an error received. How to handle NaN or infinite value during assign to hour, min or sec?
Here is my code:
private func secondsToFormattedString(totalSeconds: Float64) -> String{
let hours:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 86400) / 3600)
let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
if hours > 0 {
return String(format: "%i:%02i:%02i", hours, minutes, seconds)
} else {
return String(format: "%02i:%02i", minutes, seconds)
}
}
Another option is to use a formatter for this, I just wanted to convert a Double to an Int to make it easier to display in my UI so a NumberFormatter
was perfect, my Double was NaN so that's what the NumberFormatter
provided me, rather than the fatalError
that the Int 'cast' provided (why doesn't it return an optional like Int(String) does?)
But in the context of this question a DateFormatter
is a great solution, which would do the whole function's work for you (bear in mind that creating DateFormatter
s is a little costly so you wouldn't want to create one for every string formatting you do but keep it hanging out if it makes sense)
You should check if totalSeconds
is a valid value, like:
guard !(totalsSeconds.isNaN || totalSeconds.isInfinite) else {
return "illegal value" // or do some error handling
}
And check this: Convert Float to Int in Swift
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With