need code-sample using "NumberFormatter"

Is there anybody who can show me how to use NumberFormatter.

I would like to use it to transform input from TextField into NSNumber.

Answered by Apfelgruen in 655278022
Dear jjatie

thank you very much, I copied your code and it works well. So I can continue.


this is one example of transferring an amount of payment
I'm using the MVVM design pattern.
In the View.swift file

Code Block
struct ContentView: View {
@State var amount: String = ""
var body: some View {
VStack(alignment: .leading) {
TextField("Enter amount...", text: $amount, onEditingChanged: { (changed) in
print("amount onEditingChanged - \(amount)")
}) {
print("amount onCommit")
}
Text("Your amount: \(amount)")
}.padding()
}
}


//NumberFormatter in ViewModel.swift
assuming the variable amount = "USD1,234.57"
Code Block
var numberInString = amount
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.currencyISOCode
numberFormatter.locale = Locale(identifier: "en_US")
if let number = numberFormatter.number(from: numberInString) {
print("this is the final number:", number)
}


Result:
this is final number: 1234.57
I'm guessing you don't actually want an NSNumber as Swift provides it own number types (Int, Double, etc.). Here is an example that uses Int, though this can be simply modified by setting formatter.allowFloats = true and changing number's type to Double.

Code Block
struct ContentView: View {
static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.allowsFloats = false
return formatter
}()
@State var number: Int = 0
var body: some View {
TextField(
"Number Field",
value: $number,
formatter: Self.formatter,
onCommit: {
print(number)
}
)
.keyboardType(.numberPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
}

Accepted Answer
Dear jjatie

thank you very much, I copied your code and it works well. So I can continue.


need code-sample using "NumberFormatter"
 
 
Q