NumberFormatter在德语区域设置下无法正常工作的排查求助
排查Android NumberFormatter在德语下无法正常生成紧凑记数格式的问题
问题根源
你用NumberFormatter实现的K/M/B/T紧凑记数在德语下失效,核心原因有两个:
- 本地化规则差异:德语区域的标准紧凑记数默认采用「千位分隔+无字母后缀」的形式(比如1345会显示为
1,234而非1.3K),而Notation.compactShort()会严格遵循各区域的本地化标准,导致和其他欧洲语言表现不一致。 - Locale获取偏差:你用
Resources.getSystem().configuration.locales.get(0)获取的是系统全局Locale,不一定等于当前App的实际运行Locale,可能导致格式逻辑判断失误。
解决方案
1. API 33+ 最优写法(强制带后缀)
Android 13(API33)新增了Notation.compactShortWithSuffix(),可以直接强制所有区域使用带字母后缀的紧凑记数格式:
private fun formatCount(number: Long, context: Context) = NumberFormatter.with() .notation( if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Notation.compactShortWithSuffix() } else { Notation.compactShort() } ) .decimal(NumberFormatter.DecimalSeparatorDisplay.ALWAYS) .precision(Precision.fixedFraction(1)) // 改用App当前Locale,避免系统全局Locale干扰 .locale(context.resources.configuration.locales.get(0)) .format(number) .toString()
2. 兼容API 30-32的降级处理
如果要支持更低版本,针对德语单独做手动格式处理:
private fun formatCount(number: Long, context: Context): String { val locale = context.resources.configuration.locales.get(0) // 德语单独处理,其他语言沿用原有逻辑 if (locale.language == "de") { return when { number >= 1000000000 -> String.format(locale, "%.1fB", number / 1000000000.0) number >= 1000000 -> String.format(locale, "%.1fM", number / 1000000.0) number >= 1000 -> String.format(locale, "%.1fK", number / 1000.0) else -> number.toString() } } return NumberFormatter.with() .notation(Notation.compactShort()) .decimal(NumberFormatter.DecimalSeparatorDisplay.ALWAYS) .precision(Precision.fixedFraction(1)) .locale(locale) .format(number) .toString() }
3. 修正Locale获取逻辑
把Resources.getSystem()替换为当前Context的Resources,确保获取的是App的实际运行Locale:
// 错误写法 .locale(Resources.getSystem().configuration.locales.get(0)) // 正确写法(二选一) .locale(context.resources.configuration.locales.get(0)) .locale(Locale.getDefault())
内容的提问来源于stack exchange,提问作者Wahib Ul Haq
相关产品推荐
相关产品推荐

