1

I have a string say 1234567890 and I want to append the , character to positions in the String so that the string becomes 1,234,567,890. How do I go about it?

If the string has only 4 character like 1234, I could do:
if (str.length() >= 4) {
    str= str.substring(0, str.length()-3)+","+str.substring(str.length() - 3, str.length());
}

but how would I do it in case the string is 1234567890? Thanks.

Delali
  • 858
  • 2
  • 16
  • 24
  • 2
    I don´t know Java, but isn´t there st. like PHPs `number_format` function? – pavel Jul 24 '14 at 07:53
  • Pass the `String` to `StringBuilder`, then insert the `,` at the appropriate points. Use `StringBuilder#toString` to get the value back. Of course, you could just use a `NumberFormat`... – MadProgrammer Jul 24 '14 at 07:53
  • I think, u would like to format the number? http://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java – Zaw Than oo Jul 24 '14 at 07:54

1 Answers1

2

You can use DecimalFormat. First turn the String to a number, then format it:

double number = Double.parseDouble(numberString);
DecimalFormat formatter = new DecimalFormat("#,###");
String formattedString = formatter.format(number);
sina72
  • 4,931
  • 3
  • 35
  • 36
  • Yea, this one actually works. It is simple and easy to understand. Thanks. – Delali Jul 24 '14 at 08:00
  • Yes, the underlying problem was how to group thousands. If it solved your problem, please consider accepting my answer. – sina72 Jul 24 '14 at 08:04