I am currently using a NumberFormatter for a textfield that is meant to accept a currency amount from the user.The text field starts with the "$0.00"
A problem I've been having is that if the dollar sign in the textfield is deleted, the value is saved as 0.00.
I believe that the problem has to due with how I set up the NumberFormatter, but I wasn't able to get much help from searches online.
var formatter: NumberFormatter{
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter
}
The Textfield:
TextField("Amount of regular paycheck", value: $amount, formatter: formatter)
.keyboardType(.decimalPad)
.background(Color.white)
.textFieldStyle(.roundedBorder)
Storing currency as a double can lead to problems. Best practice is to store it as an integer as cents.
I use the following for my cash fields. The textfield state is stored as $dollarText. The currency value is stored as $cents.
If the user enters a properly formatted $1.23 string that the .currency format can recognize, then it converts that to an integer. If the user enters a double such as 1.23 then it converts that text to an integer and replaces the $dollarText with a properly formatted text string.
and a couple of extensions: