Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to in calculate percentages in swift?

Tags:

swift

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.

like image 755
user9347880 Avatar asked May 03 '18 23:05

user9347880


People also ask

How do you calculate percentage in Swift?

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.

What is the percentage formula?

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%.

What does percent mean in Swift?

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.


1 Answers

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.

like image 196
rmaddy Avatar answered Nov 29 '22 01:11

rmaddy