kotlindecimalformatnumberformatter

How to create a Kotlin Decimal Formatter


I would like to create a decimal formatter that would display up to 2 decimal digits, with a given separator.

For example with separator ","

input -> output
3.0   -> "3"
3.1   -> "3,1"
3.14  -> "3,14"
3.141 -> "3,14"
3.149 -> "3,15"

I would like to do this in Kotlin, I guess I must use DecimalFormat but don't understand how to do so. Could you please help me?


Solution

  • The code below was tested against all your examples and seemed to work well:

    val locale = Locale("en", "UK")
    val symbols = DecimalFormatSymbols(locale)
    symbols.decimalSeparator = ','
    val pattern = "#.##"
    val decimalFormat = DecimalFormat(pattern, symbols)
    val format = decimalFormat.format(3.14)
    println(format)  //3,14
    

    To set a specific separator in your DecimalFormat, you can use setDecimalSeparator.

    Pay attention to the pattern as # means:

    A digit, leading zeroes are omitted

    You can obviously change the locale to your fitting.

    More information here.