1

CurrencyTextField Issue with Double Precision

I read before that the problem could be related to floating-point sensitivity, but I couldn't find any solution to it."

I am facing an issue with my CurrencyTextField view in SwiftUI that accepts double values. When I enter a value such as 0.92, it gets stored as 0.92000000000000004 in the Double data type. This causes unexpected output and I'm not sure why this is happening.

I have tried rounding the value using the rounded() method but it didn't work. As a beginner in programming, I'm not sure how to resolve this issue.

I can't share the entire code because I am working on a confidential project for which I signed an NDA. Here is the simplified version of the code for CurrencyTextField:

public struct CurrencyTextField<Content>: View where Content: View {
  @Binding var value: Double

  // other properties excluded for brevity

  @State private var money: NSNumber?

  public init(
    value: Binding<Double>,
    // other parameters excluded for brevity
  ) {
    self._value = value
    // other assignments excluded for brevity

    if self.value > 0 {
      self._money = State(initialValue: NSNumber(value: self.value))
    }
  }

  public var body: some View {
    // other code excluded for brevity

    FormatSumTextField(
      numberValue: self.$money,
      // other parameters excluded for brevity
    )
    .onChange(of: self.money) { moneyValue in
      self.value = moneyValue?.doubleValue ?? 0
    }

    // other code excluded for brevity
  }
}

I also tried rounding the value in the onChange method like this:

.onChange(of: self.money) { moneyValue in
  self.value = moneyValue?.doubleValue.rounded() ?? 0
}

However, it didn't work as expected. I expected the value to be stored as 0.92 in the Double data type.

Any help would be much appreciated. Thank you!

Specter
  • 11
  • 1
  • 1
    Use Decimal instead of Double (and instead of NSNumber) – Joakim Danielson Mar 17 '23 at 09:10
  • See [is floating point math broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) to learn about how floating point numbers work. – Dávid Pásztor Mar 17 '23 at 10:06
  • I was using NSNumber because the formatting library I was using only accepted it, and I wasn't using Decimal because it wasn't Comparable. However, I think it's best to overcome these problems and switch to Decimal. Thank you for your support! – Specter Mar 17 '23 at 12:55

0 Answers0