Ben Stauffer
Ben Stauffer

Reputation: 33

How to return 0 instead of Nan in Swift?

let need = (Singleton.shared.getTotalExpense(category: .need) / Singleton.shared.getTotalIncome()) * 100
      needsLabel.text = "" + String(format: "%.f%%", need)

If total expenses and total income are both zero I don't want NaN to be returned. How can I make it so if need = Nan, it returns 0

Upvotes: 0

Views: 1807

Answers (1)

New Dev
New Dev

Reputation: 49590

You'd need to conditionally check if you both numerator and denominator are zero, which is one reason it would result in NaN, and conditionally assign zero to the result.

let expenses = Singleton.shared.getTotalExpense(category: .need)
let income = Singleton.shared.getTotalIncome()

let need = expenses == 0 && income == 0 ? 0.0 : expenses / income * 100

You could also check if the result of division is NaN (which could be if any of the operands was NaN):

let ratio = expenses / income * 100
let need = ratio.isNaN ? 0.0 : ratio

Be aware that you might also need to handle a scenario where you divide non-zero by zero - this would result in Inf - it all depends on your use case:

if ratio.isInfinite {
  // do something else, like throw an exception
}

Upvotes: 2

Related Questions