0

I think I did something wrong with my algorithm that I was trying to split my number 150000 into thousands with for loop. I want the output to be like 150,000. I was just having trouble coming up with a nice way doing it.

Here are my codes:

public class testing {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String l= "150000";
        for(int i=l.length();i<0;i--){
            if ((i/4)==0){
                l=","+l.substring(i, l.length()-1);
            }
        }
        System.out.println(l);
    }

}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Nate Lee
  • 17
  • 7

1 Answers1

2

I want the output to be like 150,000. I was just having trouble coming up with a nice way doing it.

Use DecimalFormat and set the grouping separator of DecimalFormatSymbols:

DecimalFormatSymbols symbol = new DecimalFormatSymbols();
symbol.setGroupingSeparator(',');
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(symbol);
System.out.println(format.format(150000));//print 150,000

Edit

As per your comments, if you really want to use a loop, here one that would work :

String l = "150000";
String result = "";
for (int i = 0; i < l.length(); i++) {
    if (i != 0 && i % 3 == 0)
        result = result + "," + l.charAt(i);
    else
        result = result + l.charAt(i);
}
System.out.println(result);

Which would print 150,000.

Your actual loop was never reached, the condition was i < 0 but i was starting at l.length() which can never be less then 0. The i/4 is also wrong, you want to use modulo instead. I also believe it should be i % 3 instead of i % 4. You will also need to check if this is the beginning of the string else it will put a comma at begining.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • I see what you did there. Unfortunately, I am not allowed to use format function for my project in class. I have to figure a way with for loop and substring to manually separate the number into thousands. Thank you by the way. – Nate Lee Apr 12 '15 at 18:19