UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 18 Completed

Forums > 100 Days of SwiftUI

I tried to find a fix for the problem where the division of the total cost by the number of payers results in slightly less than the total cost being paid e.g. $10 total cost divided by 3 payers results in $3.33 per person when it should really be $3.34 (a few extra cents tip, rather than a slightly lower tip - especially when 0% tip is selected).

I can identify when the problem happens by doing the calculations with Decimal instead of Double but, sadly, I couldn't come up with a nice, elegant way to adjust the per person payment amount and be able to inform the user that a little extra needed to be paid in total.

If anyone managed to come up with a nice solution I'd love to see it.

2      

I think I tried messing with pennies. But then I realized I HATE pennies!

Instead, I added a toggle named "Round Up?" next to the per person cost. It's on by default. This is my version of a nice solution.

 @State private var roundUp = true // Attach this to the toggle. Prefer to round up!
 var checkValue: Double {
       guard let value = Double(checkAmount) else { return 0 }  // read the string. Total check value
       return value > 0 ? value : 0.0 // Positive values only.
}
var basicPayment: Double { (checkValue + tip) / Double(totalSeats) } // standard formula
var totalPerPerson: Double { roundUp ? basicPayment.rounded(.up) : basicPayment } // Round up!

That being said, you should probably take a close look at this forum message:

Message: Don't use Doubles for Currency

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.