NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

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.


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


Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Reply to this topic…

You need to create an account or log in to reply.

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.