Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3:fatal error: Double value cannot be converted to Int because it is either infinite or NaN

Tags:

swift

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)
    }
}
like image 449
Shahbaz Akram Avatar asked Feb 02 '17 10:02

Shahbaz Akram


2 Answers

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 DateFormatters 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)

like image 32
CMash Avatar answered Sep 18 '22 18:09

CMash


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

like image 112
Andreas Oetjen Avatar answered Sep 17 '22 18:09

Andreas Oetjen