Add commas or point every 3 digits using kotlin

Viewed 9076

I want to add commas or point every 3 digit in EditText input.

Example :

  • input : 1000. Output : 1.000
  • input : 11000. Output : 11.000
7 Answers

If you are on the JVM you can use

"%,d".format(input)

which gives 11,000 for input 11000. Replace , with any delimiter you require.

If you want to use predefined number formats, e.g. for the current locale, use:

java.text.NumberFormat.getIntegerInstance().format(input);

Be also sure to check the other format instances, e.g. getCurrencyInstance or getPercentInstance. Note that you can use NumberFormat also with other locales. Just pass them to the get*Instance-method.

Some of the second variant can also be found here: Converting Integer to String with comma for thousands

If you are using it via Javascript you may be interested in: How do I format numbers using JavaScript?

System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));

Based on Splitframe answer above, did a simplified version (without the var):

fun Int.formatDecimalSeparator(): String {
    return toString()
        .reversed()
        .chunked(3)
        .joinToString(",")
        .reversed()
}

And added some tests:

    @Test
    fun whenFormatDecimal_thenReturnFormatted() {
        mapOf(
            1 to "1",
            12 to "12",
            123 to "123",
            1234 to "1,234",
            12345 to "12,345",
            123456 to "123,456",
            1234567 to "1,234,567",
            12345678 to "12,345,678",
            123456789 to "123,456,789",
            1234567890 to "1,234,567,890",
        ).forEach { (test, expected) ->
            val result = test.formatDecimalSeparator()
            assertEquals(expected, result)
        }
    }

In my case is a KMM project, and we don't support other languages, so it does the job. A better solution I would say to create an expect Util class and each platform implement the formatter taking account of the user Locale, etc.

This is a simple way that able you to replace default separator with any characters:

val myNumber = NumberFormat.getNumberInstance(Locale.US)
   .format(123456789)
   .replace(",", "،")

I used this for a non JVM Kotlin environment:

fun formatDecimalSeperators(number :String) :String {
    var index = 1
    return number
            .takeIf { it.length > 3 }
            ?.reversed()
            ?.map { if (index++ % 3 == 0) "$it," else it }
            ?.joinToString("")
            ?.reversed()
            ?.removePrefix(",")
            ?: number
}

You can also use @Roland answer in Android String Resources to format it:

<string name="answer_count">%,01d answers</string>

For a method without getting Locale, you can use an extension to convert your Int into a formatted String like this below :

fun Int.formatWithThousandComma(): String {
    val result = StringBuilder()
    val size = this.toString().length
    return if (size > 3) {
        for (i in size - 1 downTo 0) {
            result.insert(0, this.toString()[i])
            if ((i != size - 1) && i != 0 && (size - i) % 3 == 0)
                result.insert(0, "\'")
        }
        result.toString()
    } else
        this.toString()
}

Related