Reputation: 33
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
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