String commas

Discussion in 'Plugin Development' started by FurmigaHumana, Aug 26, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    FurmigaHumana

    Hi,

    Someone knows how do I force a integer to be showed with commas?

    For exemple, I print a random number in the console, so I use this code:
    int money = 2147289843
    log.info("You have: " + money);

    The result will be:
    You have: 2,147,289,843

    Ok, no problem there, but sometimes my code return as a String, so I need to manualy convert to integer, then i do:

    int money = Integer.parseInt("2147289843");
    But the result here don't have the commas, looking like:
    You have: 2147289843 <ugly!

    Halp? Maybe a pattern? I dunno how to use patterns :C
     
  2. Try something like this:
    Code:
    String mon = money.toString();
    String tmp = "";
    for(int i = 0; i < mon.length(); i++) {
        tmp += mon.charAt(i);   
        if(i % 3 = 0) {
            tmp += "," + mon.charAt(i);
    }
    }
    Something like that, just wrote this without checking if it works, so i think it will contain bugs...:/
    But it shouldn't be to difficult to fix them:D
     
    FurmigaHumana likes this.
  3. Offline

    FurmigaHumana

    So simple :D

    Thank you :)

    Final code:
    Code:
        public String commas(String str) {
            String temp = "";
            for (int i = 0; i < str.length(); i++) {
                temp += str.charAt(i);
                if (i % 3 == 0) {
                    temp += ",";
                }
            }
            return temp.substring(0, temp.length() - 1);
        }
     
  4. Offline

    Courier

    Lol no... Just use Formatter.
    Code:java
    1. public static String addCommas(int num)
    2. {
    3. return String.format("%1$,d", num);
    4. }
    Or
    Code:java
    1. int money = Integer.parseInt("2147289843");
    2. log.info(String.format("You have: %1$,d", money));
     
Thread Status:
Not open for further replies.

Share This Page