Monday, September 7, 2009

Numbers with commas

Here's a simple method to include commas after every third digit from the right:

public class Utilities{
private static int startingPivot;
private static final int INDENT = 3;

public static StringBuffer decimalize(int input){
String conv = Integer.toString(input);
StringBuffer sb = new StringBuffer();

int commaIndex = conv.length() / INDENT ;
int strLength = conv.length();

startingPivot = (strLength) - (commaIndex * INDENT );
if (startingPivot == 0) {
startingPivot = INDENT ;
}

for (int index = 0; index < strLength; index++) {
if (index == startingPivot) {
sb.append(",");
startingPivot = startingPivot + INDENT;
}
sb.append(conv.charAt(index));
}
return sb;
}
}
You may try this code by making this method call

System.out.println(Utilities.decimalize(1234567890));
and the output is 1,234,567,890
NEAT :D

0 comments:

Post a Comment