iosswiftnumberformatter

Swift NumberFormatter just for thousand


I want to separator in 1000 after 1, but I'm getting separator for numbers >=10000 How I'm doing it:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.string(for: myNumber)

what I'm getting:

(lldb) po formatter.string(for: 1000)
▿ Optional<String>
  - some : "1000"

(lldb) po formatter.string(for: 10000)
▿ Optional<String>
  - some : "10 000"

why there is no separator in 1000?


Solution

  • You ask:

    why there is no separator in 1000?

    This pattern, of omitting the grouping separator when there are only four digits, is not uncommon for languages that use a space as the separator.

    As Exceptions to digit grouping says:

    The International Bureau of Weights and Measures states that “when there are only four digits before or after the decimal marker, it is customary not to use a space to isolate a single digit”.

    You will see this pattern in several locales that use space as the grouping separator.


    This formatting is based upon the device’s settings (as represented by your current Locale). You can test to see what it looks like for other users in other locales by just temporarily changing your device settings.

    I would be wary about manually adjust locale property of the formatter for desired output: Sure, one may do that for diagnostic purposes, but generally you do not want to change the locale of the formatter (with the obvious exception where you need some invariant format, for example, storing results in persistent storage or sending to a server).

    Always use the device’s current locale so you honor the number formatting wishes of the end user.