0

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

Pete
  • 213
  • 1
  • 13
  • I took your code and run it on the playground and didn't find any issue with combining CGFloat, but I found that you can `value: CGFLoat` as `@Binding` meaning you store the value, not in that View. So, my guess is something wrong there. You can check it by changing `@Binding` to `@State`. If you can share the code where you use that View, it can help understand where it the issue. – Oleg Feb 15 '23 at 11:04
  • The floating point types may have such a problem. Try to use `Double` or some `round`s. – Andrew Bogaevskyi Feb 15 '23 at 11:04
  • Oleg - I also ran the code with @State - same issue. 0.7 + 0.1 = 0.7999… – Pete Feb 15 '23 at 11:46
  • @Andrew - switched to Double - same issue. This is really odd. – Pete Feb 15 '23 at 11:50
  • 1
    @Jessy - yes, that answers it. Thanks for the clarification! – Pete Feb 15 '23 at 11:52

0 Answers0