Search code examples
kotlinnumber-formatting

How to format number to have thousands separator?


As input, I get a number, for example 1000000, it needs to be converted into a String that will look like this: 1.000.000

Also, the number can be 750000 or any other, it must be converted to 750.000 and so on (the number can be either less than 10 thousand or more than 10 million)

How can I do that?


Solution

  • A simple way to do this would be using java.text.DecimalFormat:

    fun formatter(n: Int) =
        DecimalFormat("#,###")
            .format(n)
            .replace(",", ".")
    
    println(formatter(1000000)) // => 1.000.000
    println(formatter(750000))  // => 750.000
    

    However, do note that the dot (.) symbol is commonly used as a Decimal separator (or monetary decimal separator)

    So I would advice using , instead of of ..

    Try it online!


    Update:

    If your intention is having a German locale (Thanks @AndrewL) formatting, then configure the DecimalFormatSymbols with the correct locale:

    fun formatter(n: Int) =
        DecimalFormat("#,###", DecimalFormatSymbols(Locale.GERMANY)).format(n)
    

    Try it online!