I am creating an expense ios application. I am using a Progress View to display how much income the user has left. So for example, if the user puts $100 income, and $30 expense, I'd like the bar to be 70% full. How do I calculate this?
I had originally put
let fractionalProgress = Float(expenseFloat!)/Float(balanceFloat!)
but this doesn't return the right value needed.
In your example with a balanceFloat of 100 and an expenseFloat of 30 this gives (100 - 30) / 100 which is 0.7 . Of course you would multiple this result by 100 if you wish to show a percentage. Better yet, use a NumberFormatter setup with a . percent style.
Percentage can be calculated by dividing the value by the total value, and then multiplying the result by 100. The formula used to calculate percentage is: (value/total value)×100%.
Note. The remainder operator ( % ) is also known as a modulo operator in other languages. However, its behavior in Swift for negative numbers means that, strictly speaking, it's a remainder rather than a modulo operation.
The formula in your question is correct if you want to know the percentage spent so far.
The percent remaining formula is "remaining balance" / "original balance".
And of course "remaining balance" is "original balance" - "total of expenses".
let fractionalProgress = (balanceFloat - expenseFloat) / balanceFloat
where balanceFloat
is the original balance and expenseFloat
is the total expenses.
In your example with a balanceFloat
of 100
and an expenseFloat
of 30
this gives (100 - 30) / 100
which is 0.7
.
Of course you would multiple this result by 100 if you wish to show a percentage. Better yet, use a NumberFormatter
setup with a .percent
style.
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