Chris Kelly
Chris Kelly

Reputation: 13

Trying to add a percentage of a variable to itself in Swift

I have a variable that is an Int (loan). I want to add 10% to it each time a button is clicked.

I've tried various methods, firstly:

loan = 50
loan = loan + loan / 100 * 10

when I print loan, it still shows 50 without the 10 percent added.

Next, I tried declaring a new Int variable (percent) to work out the percentage:

loan = 50
var percent = loan / 100 * 10
loan = loan + percent

Again, loan prints 50 and percent prints 0.

In each case, I've experimented putting the maths into brackets, but that gives the same result. I'm sure this must be a very simple fix but I can't work it out, and have had no luck googling.

Upvotes: 1

Views: 532

Answers (3)

DrDev
DrDev

Reputation: 442

first, loan should be double (cause int cannot have fractions)

Then you can do something like this:

loan = 50
loan *= 1.1

Upvotes: 0

Caleb
Caleb

Reputation: 125007

I want to add 10% to it each time a button is clicked.

You can either add 10%, or a tenth, of the original value, or multiply by 1.1:

var loan = 50.0       // including the decimal point makes it a float

...any of these will work:

loan = loan + loan * 0.1
loan = loan * 1.1
loan += loan * 0.1
loan *= 1.1

Again, "loan" prints 50 and "percent" prints 0.

That's because loan was declared as an integer type, and the other values in your calculation were also integers, so the compiler inferred that percent should also be an integer. You could fix that by explicitly setting the type of either loan or percent to Float or Double, like this:

var percent : Float = loan / 10

Or you can do it implicitly, as I did up top, by setting loan to 50.0 instead of 50. The compiler will understand that 50.0 is a Float, so it'll infer that loan is a Float, which would then cause calculations done with loan to be of that type, and percent would also be a Float.

Upvotes: 0

Charles Srstka
Charles Srstka

Reputation: 17060

Your problem is that loan is declared as an Int. Ints cannot have fractional components, so when you try to divide 50 by 100, the answer, 0.5, has its fractional component stripped off, making 0. Times that by 10, and it's still zero, so when you add it to loan, it doesn't change the result.

You can solve this by declaring loan as a Double instead of an Int. You can also just multiply by 1.1 to add 10%.

var loan: Double = 50

loan *= 1.1

Upvotes: 3

Related Questions