iOS国际化纯数字:使用NumberFormatter会产生哪些格式变更?
Hey there! Let's walk through the potential format changes you might encounter when using NumberFormatter on plain, unmodified numeric values (like 1000) that don't represent currency, time, or other specialized data—especially when you want to keep them as simple, unseparated digits.
Common Format Changes Introduced by NumberFormatter
Automatic Thousand Separators: By default,
NumberFormatterapplies locale-specific grouping separators to large numbers. For example:- In
en_USlocale, 1000 becomes1,000 - In
de_DElocale, it becomes1.000 - In locales like
hi_IN, grouping follows a non-standard pattern (e.g., 100000 becomes1,00,000)
This is likely the primary behavior you're aiming to avoid.
- In
Unwanted Decimal Places: If you don't explicitly configure fraction digit settings, the formatter might add trailing zeros based on locale defaults or accidental configuration. For instance, if
minimumFractionDigitsis set to 2, 1000 could turn into1,000.00(en_US) or1.000,00(de_DE).Localized Digit Systems: In certain locales, the formatter might convert Arabic numerals (0-9) to other script digits. For example, using an Arabic locale (
ar_SA) would turn 1000 into١٠٠٠.Incorrect Number Style Application: If you accidentally set a
numberStylelike.currency,.percent, or.spellOut, your plain number will be transformed entirely—e.g., 1000 becomes$1,000.00(currency) orone thousand(spellOut).
How to Keep Numbers as Plain, Unseparated Digits
If you want to use NumberFormatter but avoid all these formatting changes, configure it with these key settings:
let plainNumberFormatter = NumberFormatter() plainNumberFormatter.numberStyle = .none // Disables all automatic formatting plainNumberFormatter.minimumFractionDigits = 0 // Ensures no trailing decimal zeros plainNumberFormatter.maximumFractionDigits = 0 // Limits to integer values only // You can set a specific locale if needed, or use Locale.current // Example usage if let formattedString = plainNumberFormatter.string(from: 1000 as NSNumber) { print(formattedString) // Outputs "1000" regardless of locale }
Setting numberStyle = .none is critical here—it tells the formatter to treat the number as a raw, unformatted value, skipping all grouping, decimal, or script conversions.
内容的提问来源于stack exchange,提问作者kmell96

