0

Possible Duplicate:
How can I format a String number to have commas and round?

I have a string variable (That is a number in string format) and now I want to use a comma for separation for every three digits. how can I do it? My technology is Struts2

Community
  • 1
  • 1
AFF
  • 1,515
  • 4
  • 21
  • 35

4 Answers4

0

Use NumberFormat:

long num = Long.valueOf("1234567890");
String numWithCommas = java.text.NumberFormat.getInstance().format(num);

Edit:

The above code snippet will default to using the user's current locale (which I'm guessing is probably what you'd want—you want the number to be formatted in a way the user is used to seeing). If you want to set a specific locale you can pass an instance of Locale to getInstance(). There are a bunch of static instances available in the Locale class for your convenience:

// Always prints with comma as separator
java.text.NumberFormat.getInstance(Locale.ENGLISH).format(num);
// => 1,234,567,890

// Always prints with period as separator
java.text.NumberFormat.getInstance(Locale.GERMAN).format(num);
// => 1.234.567.890
DaoWen
  • 32,589
  • 6
  • 74
  • 101
  • -1; It all depends on the Locale being used. The `NumberFormat` returned by `getInstance()` uses the current Locale. You should explain how to set the correct format. – maba Aug 16 '12 at 07:14
  • maba - You're right, I slacked off and didn't explain about locales. I've updated it now with an example. – DaoWen Aug 16 '12 at 07:26
0

For Example:turn 100000 to 100,000

public class number
{
    public static void main(String args [])
    {
        double d = 123456.78;
        DecimalFormat df = new DecimalFormat("###,### ");
        System.out.
        println(df.format(d));
    }
}
keep fool
  • 101
  • 4
0

Using StringBuilder with its insert() method you can achieve this.

StringBuilder sb = new StringBuilder("123456987098");
int j = sb.length();

for(int i=3 ; i<j ; i=i+4){

       sb.insert(i,",");

       }

System.out.println(sb.toString());
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
-1
    String string = "1,234,567";
    String[] splits = string.trim().split(",");
    int num = 0;
    for (String split : splits)
    {
        num = (num * 1000) + Integer.parseInt(split.trim());
    }
    System.out.println(num); // prints 1234567
Binil Thomas
  • 13,699
  • 10
  • 57
  • 70