15

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
  • 7,766
  • 8
  • 46
  • 61
Ahmed
  • 177
  • 1
  • 6

4 Answers4

32

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
  • 20,248
  • 2
  • 47
  • 80
2

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

0

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
  • 917
  • 9
  • 28
-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()
}