I'm trying to figure out Swift number formatting. Seems there are multiple flavors of doing this task.
I think the newer (I go find the version #s later) version is spelled formatted(). Whereas an older version is NumberFormatter.
The Apple Docs show iOS 2.0 - that's 1999ish - right? So last century!
Then there are the NumberFormatter.Style enumeration cases - for example decimal.
"For example, in the en_US locale, the number 1234.5678 is represented as 1,234.568"
How is that example any kind of useful information?
The NEW (iOS 15 - 2021) formatters - in action above.
I really thought I would see a value like 14.5, instead I get 10. Aparently precision is not fractional precision. Well ... back to the docs.
The .number.precision(.fractionLength(1) ) is the trick.
With iOS 15 and newer we have Data Formatting. Which uses the generic method formatted( ) along with the optional FormatStyle protocol.
I'm not finding the Apple documentation to be very helpful. It is right about on the Decimal.FormatStyle page that the documentation could use a real code example - right!
Clicking around a bit you can find that one style is currency and it needs a 'code' - what type of code... you cannot learn. I did find an example online and tried "USD" and got the dollar sign!
I've no idea where one would go to find the allowable and typical use cases for currency codes.
Reading Sarunw's wonderful article (see above) he notes that the old formatters were converters - that operated by converting the numbers into a String representation. Oh - good to know! The new iOS 15 formatters are not that! He states: " I think it easier to think of the old API as a converter and this new API as a real data formatter."
The new technique removes the (often expensive) type creation process (and possible caching). The new formatter is an extension of Data and provides a quick and easy formatted( ) method. It is a declarative style method - you can just say what properties of a Date you want to be shown and not worry about the details of how to do that formatting.
You are also getting some wonderful compile-time type validity checking and uniformaty. See Sarunw's article for more examples.
Note: if you are getting compile errors - you might be doing what I was... mixing the two format styles together - it's not going to work well. Check the top of your Apple documentation page for the Framework your style is associated with. Data Formatting is the NEW stuff!
found on Twitter @DKanunnikoff