28

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

Example :

  • input : 1000. Output : 1.000
  • input : 11000. Output : 11.000
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ahmed
  • 307
  • 1
  • 3
  • 7

10 Answers10

49

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?

Roland
  • 22,259
  • 4
  • 57
  • 84
  • Works if delimiter is a comma, but for apostrophe' I get an UnknownFormatConversionException. – digory doo Feb 23 '23 at 18:30
  • Please check [the Formatter Javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html) to see which flags are supported or how the formatting string can be constructed in detail. The ',' is just one of the possible flags (locale-specific grouping separator) . The chapter [Number Localization Algorithm](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#L10nAlgorithm) contains specific details about number formatting. – Roland Feb 23 '23 at 20:50
14

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.

William Da Silva
  • 703
  • 8
  • 19
4

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

val myNumber = NumberFormat.getNumberInstance(Locale.US)
   .format(123456789)
   .replace(",", "،")
Kaaveh Mohamedi
  • 1,399
  • 1
  • 15
  • 36
3

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

1

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
}
Splitframe
  • 406
  • 3
  • 16
0

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

<string name="answer_count">%,01d answers</string>
MBH
  • 16,271
  • 19
  • 99
  • 149
0

This might help

fun format(amount):String{
    val numberFormat = DecimalFormat("#,###.00")
    return numberFormat.format(amount)
}
Sourav
  • 312
  • 1
  • 8
0

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
       }
    
    }
    
Leuss
  • 331
  • 2
  • 3
0

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

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