I wrote a separate field component to solve the percent field problem. Apparently, this is generally necessary with decimal numbers. Or is there a simpler solution?
Decimal point formatting is a general problem and affects not only percentages but all floating-point numbers. Whether format or formatter is used is irrelevant.
I have a formatter that only allows values up to a maximum and has one decimal place.
let limitedFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.minimum = 0
formatter.maximum = 13.9
formatter.generatesDecimalNumbers = true
formatter.maximumFractionDigits = 1
formatter.numberStyle = .decimal
return formatter
}()
When the focus of the field is removed, the formatter becomes active and the behavior is as expected. However, if the view is immediately exited using dismiss(), as in the previous example, it doesn't work.
That's not entirely correct, because the formatter only does half its job and checks whether the maximum has been exceeded, but ignores the decimal places, as in the other example.
However, it seems to work if you append arbitrary decimal places to the maximum value. Example: the maximum is 13.9, and if I enter 13.9888888, it becomes 13.9.
It gets even stranger: if you set a minimum value in the formatter and then enter a value outside that range, the result is nil. With a minimum value of 0, the first digit is used, as long as it's not higher than the maximum value; otherwise, the result is nil again.
Christian