在 Android 中实施适当的单个小数位格式化程序

问题描述 投票:0回答:1

我需要创建一个十进制格式化程序,最多显示 1 个十进制数字,并带有与区域设置兼容的分隔符。

例如:

0 --> 0.0 or 0,0
0.0 --> 0.0 or 0,0
4 --> 4.0 or 4,0
3.5 --> 3.5 or 3,5

我需要在 Kotlin for Android 中实现它。我最初尝试使用

DecimalFormat
但当输入为“0.0”

时此解决方案不起作用
 DecimalFormat("#.0").format(inputNum.toDouble())

什么是更合适的 Android 方式?

android kotlin locale decimalformat numberformatter
1个回答
0
投票

在尝试各种解决方案后,我找到了使用 NumberFormatter 而不是

DecimalFormat
作为推荐方法的合适方法。

此 API 提供了比 android.icu.text.DecimalFormat 更多的功能,并且面向 ICU 的新用户。

private fun formatNumber(number: Double) = NumberFormatter.with()
.decimal(NumberFormatter.DecimalSeparatorDisplay.ALWAYS)
.precision(Precision.fixedFraction(1))
.locale(Resources.getSystem().configuration.locales.get(0))
.format(number)
.toString()
© www.soinside.com 2019 - 2024. All rights reserved.