Pete
Pete

Reputation: 219

Swift CGFloat Rounding Issue

I have a really baffling issue with rounding of CGFloat (and Float which is the same). When I run the following code, the increments are not always 0.1 but rather I receive the result:

plus: 0.6

plus: 0.7

plus: 0.7999999999999999

plus: 0.8999999999999999

So it is calculating 0.7 + 0.1 = 0.7999999 -> Incorrect calculation.

struct PlusMinusButtons: View {
    let min: CGFloat
    let max: CGFloat
    let step: CGFloat

    @Binding var value: CGFloat

    var body: some View {
        VStack {
            Button {
                guard value < max else { return }
                value += step
                print("plus:", value, step)
            } label: {
                Image(systemName: "plus.circle")
                    .font(.title)
            }
            .padding(.bottom)

            Button {
                guard value > min else { return }
                value -= step
                print("minus:", value, step)
            } label: {
                Image(systemName: "minus.circle")
                    .font(.title)
            }
        }
    }
}

Any ideas what can be going on here? I can make an inelegant workaround but I would rather it works correctly. I am on iOS 16.2

Upvotes: 0

Views: 24

Answers (0)

Related Questions