0

SwiftUIs TextField seems to have a rounding issue when changing the fractionalLength parameter. Someone knows how to fix it?

Example:

Entering 3.7777 after losing focus the value will be rounded to 3.8. Increasing the fractionalLength to 2 decimals and entering 3.7777 after losing the focus the value will be rounded to 3.80. The expectation would be 3,78.

The View:

struct ContentView: View {

    enum FocusField: Hashable {
        case value
    }

    @State var value: Double?
    @State var decimals: Int = 1

    @FocusState private var focusedField: FocusField?

    var body: some View {
        List {
            TextField("Placeholder", value: $value, format: .number.precision(.fractionLength(decimals)))
                .keyboardType(.decimalPad)
                .focused($focusedField, equals: .value)
            Stepper("Decimals \(decimals)", value: $decimals, in: 1 ... 10)
        }
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                Button {
                    focusedField = nil
                } label: {
                    Text("Done")
                }
            }
        }
    }
}
Carsten
  • 185
  • 9
  • [See this answer.](https://stackoverflow.com/q/71228553/7129318) You may have to use a number formatter that you create rather than trying to use `TextField's format:`. – Yrb Apr 26 '22 at 01:25

0 Answers0