Search code examples
swiftswiftuiformatting

TextField format number with wrong separator inside input


Hi I have some problem with format TextField input because I want to have same local formatting in each input and output. On image you can see that text inside TextField has different formatting. enter image description here

My simple code:

struct HomeView: View {
    @State var value: Double?
    var body: some View {
        VStack {
            Text("\(value ?? 0)")
                .font(.title)
            TextField("0.0",
                      value: $value,
                      format: .number.precision(.fractionLength(2)))
            .border(.red)
            .keyboardType(.decimalPad)
        }
    }
}

Its possible to unify this behaviour?


Solution

  • You already know how to supply a format: to the TextField. You can do the same to Text.

    Text(value ?? 0, format: .number.precision(.fractionLength(2)))
    

    You can also do the same in a string interpolation:

    Text("Some Text \(value ?? 0, format: .number.precision(.fractionLength(2))) Some Text")