What's the correct way to format a number with a given locale AND with given decimal places.
If I'd have the following code:
fun main() {
val number = BigDecimal("1000");
println(formatNumber(number,Locale("de","DE"),2)) // should print 1.000,00
println(formatNumber(number,Locale("de","CH"),3)) // should print 1'000.000
}
How should formatNumber be implemented?
I've found 2 common ways to format numbers in kotlin on the internet, but both don't fully satisfy the needs:
DecimalFormat
fun formatNumber(number: BigDecimal, locale: Locale, decimalPlaces: Int) = DecimalFormat("#,###." ("0".repeat(decimalPlaces))).format(number)
Drawback: Lacks localization
NumberFormat
fun formatNumber(number: BigDecimal, locale: Locale, decimalPlaces: Int) = NumberFormat.getNumberInstance(locale).format(number)
Drawback: Lacks Decimal places
Is there a way that ticks all boxes? I feel like NumberFormat should be the way to go, but I can't figure out how to specify the decimal places..
CodePudding user response:
You can set the maximumFractionDigits
and minimumFractionDigits
on the number format:
fun formatNumber(number: BigDecimal, locale: Locale, decimalPlaces: Int) =
with(NumberFormat.getNumberInstance(locale)) {
maximumFractionDigits = decimalPlaces
minimumFractionDigits = decimalPlaces
format(number)
}
CodePudding user response:
You can also use DecimalFormat
which indeed supports localization through the DecimalFormatSymbols
parameter:
DecimalFormat("#,###." ("0".repeat(decimalPlaces)), DecimalFormatSymbols.getInstance(locale))
.format(number)