Issue
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..
Solution
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)
}
Answered By - Sweeper