Format text field to 2 decimal places without entering a decimal (SwiftUI)

Viewed 2497

In a text field, I'd like, when a user enters a number e.g. 12345, it gets formatted as 123.45. The user never needs to enter a decimal place, it just uses the 2 right most numbers as the decimal places. The field should only allow numbers too. This is for a SwiftUI project. Thanks in advance for any assistance.

1 Answers

Because there of a two way binding between what you enter and what is being shown in the TextField view it seems not possible to interpolate the displayed number entered. I would suggest a small hack:

  • create a ZStack with a TextField and a Text View superimposed.
  • the foreground font of the entered text in the TextField is clear or white .foregroundColor(.clear)
  • the keyboard is only number without decimal point: .keyboardType(.numberPad)
  • use .accentColor(.clear) to hide the cursor
  • the results are displayed in a Text View with formatting specifier: "%.2f"

It would look like

This is the code:

struct ContentView: View {
    @State private var enteredNumber = ""
    var enteredNumberFormatted: Double {
        return (Double(enteredNumber) ?? 0) / 100
    }
    var body: some View {

        Form {
            Section {
                ZStack(alignment: .leading) {
                    TextField("", text: $enteredNumber)
                        .keyboardType(.numberPad).foregroundColor(.clear)
                        .textFieldStyle(PlainTextFieldStyle())
                        .disableAutocorrection(true)
                        .accentColor(.clear)
                    Text("\(enteredNumberFormatted, specifier: "%.2f")")
                }
            }
        }
    }
}
Related