Ahmed
Ahmed

Reputation: 327

Add commas or point every 3 digits using kotlin

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

Example :

Upvotes: 30

Views: 19180

Answers (10)

mostafa ahmadi
mostafa ahmadi

Reputation: 71

this is other solution

fun separateDigit(text: String): String {
var reversedText = text.reversed()
var formattedText = ""
while (reversedText.length > 3) {
    formattedText += "${reversedText.take(3)},"
    reversedText = reversedText.drop(3)
    }
formattedText += reversedText
return "${formattedText.reversed()}"
}

Upvotes: 0

Leuss
Leuss

Reputation: 451

Here's a an extension function taking care of your case but also

  • Decimal position

  • Language consideration

  • Flooring

    fun Number.toFormattedNumber(significantDecimalPlaces: Int = 2): String? 
    {
    
       val df = DecimalFormat(
        "#,###."+"#".repeat(significantDecimalPlaces),
        DecimalFormatSymbols(Locale.ENGLISH)
       )
       df.roundingMode = RoundingMode.FLOOR
       return try {
         df.format(this.toDouble())
       }catch (e: Exception){
         null
       }
    
    }
    

Upvotes: 0

Sourav
Sourav

Reputation: 402

This might help

fun format(amount):String{
    val numberFormat = DecimalFormat("#,###.00")
    return numberFormat.format(amount)
}

Upvotes: 5

MBH
MBH

Reputation: 16609

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

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

Upvotes: 0

William Da Silva
William Da Silva

Reputation: 723

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.

Upvotes: 16

Splitframe
Splitframe

Reputation: 434

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
}

Upvotes: 1

Kaaveh Mohamedi
Kaaveh Mohamedi

Reputation: 1795

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

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

Upvotes: 4

Andre Carvalli
Andre Carvalli

Reputation: 33

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

Upvotes: 3

Antoine Proux
Antoine Proux

Reputation: 1

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()
}

Upvotes: -2

Roland
Roland

Reputation: 23252

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?

Upvotes: 54

Related Questions