I need to create a decimal formatter that would display up to 1 decimal digit, with a Locale-compatible seperator.
For example:
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
I need to implement it in Kotlin for Android. I tried initially using DecimalFormat
but this solution doesn't work when input is "0.0"
DecimalFormat("#.0").format(inputNum.toDouble())
What's more appropriate Android-ish way?
After trying various solutions, I figured out the appropriate approach using NumberFormatter instead of DecimalFormat
as a recommended approach.
This API offers more features than android.icu.text.DecimalFormat and is geared toward new users of 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()