Inacurate calculation

I am following the 14 day beginner challenge and trying a challenge in Playground. When I pass inn 100 and multiply it with 1,13 I get 112,999999999 iso 113. Why is this?

See enclosed image

Is the Bill Splitter challenge?

Show the code you are using.

Didn’t you see the image? It’s all there.

Just so that we are both on the same page, I assume that this is related to the Lesson 9 Challenge so I’m looking for the rest of the code that should correspond to the 3 parts of the challenge.

Actually it’s the lesson 7 challenge, but that’s irrelevant i believe.You see the whole Playground, there is no more and it doesn’t calculate properly.

Tricky isn’t it. It’s to do with the way Doubles are handled.

Change your print statement to this:

print("\( printTotalWithPax(subtotal: 100) )")

and see what the result is.

That didn’t help. But I tried to change the Double to Float and that helped.

Did you have a look at the solutions provided by Chris Ching?

No, I don’t think he provides a solution for the challenges.

Yes he does. They are all available via the “Resources” heading in the “Introduction” section of the course. Select “Resources” and on that page you will see a link titled “All resources, projects and code” which takes you to a Dropbox folder structure.

Thank you for taking the time to answer this.
I found the resources and ran his playground and it does the same. When I changed to Float it is correct.

Just for interest sake, plug this code into playground and run it.

func printTotalWithTax(subTotal: Double) {
    let taxAmount = subTotal * 0.13
    print("Challenge 2 - printTotalWithTax: \(subTotal + taxAmount)")
}

printTotalWithTax(subTotal: 100)

func getTotalWithTax(subTotal: Double) -> Double {
    let taxAmount = subTotal * 0.13
    return subTotal + taxAmount
}

print("Challenge 3 - getTotalWithTax \(getTotalWithTax(subTotal: 100))")

func calculateTotalWithTax(subTotal: Double, tax: Double) -> Double {
    let taxAmount = subTotal * tax
    return subTotal + taxAmount
}

print("Challenge 4 - calculateTotalWithTax \(calculateTotalWithTax(subTotal: 100, tax: 0.13))")

func printTotalWithTax2(subtotal: Double) -> Double {
    let taxRate: Double = 0.13
    return subtotal + (subtotal * taxRate)
}

print("\(printTotalWithTax2(subtotal: 100))")

You would think that the result should be the same as what you got when the variables are defined as Doubles. The only difference is that I have used a tax rate that is 0.13 or 13% of the total. This code gives you the right answer in all cases.

It goes to show that Doubles behave oddly in Swift depending on the way they are used. Why? I have no idea.