I have written a string number formatter. I would like to know if this can be improved and any suggestions with how it's done.
The purpose of this function is to convert a double that has been converted to a string, using String.valueOf
to a accounting style formatted number.
/**
* this function formats a number string to show commas and an arbitrary amount
* of decimal places
* @param string the number String
* @param decimal the decimal precision
* @return
*/
private String formatNumberString(String string, int decimal) {
char[] num = string.toCharArray();
char[] reverse = reverse(num);
int cnt = 0;
List<Character> chars = new ArrayList();
boolean fd = false;
int fCnt = 0;
if (contains(reverse, '.')) {
for (char a : reverse) {
if (!fd) {
chars.add(a);
} else {
if (fCnt == 3) {
chars.add(',');
fCnt = 0;
}
chars.add(a);
fCnt++;
}
if (a == '.') {
fd = true;
}
}
} else {
for (char a : reverse) {
if (fCnt == 3) {
chars.add(',');
fCnt = 0;
}
chars.add(a);
fCnt++;
}
}
char[] fin = new char[chars.size()];
int cntr = 0;
for (Character ch : chars) {
fin[cntr++] = ch;
}
String finall = String.valueOf(reverse(fin));
if (decimal == 0) {
int dot = finall.indexOf(".");
finall = finall.substring(0, dot);
}
if (finall.equals("0") || finall.equals("0.0") || finall.equals("0.00")) {
finall = " - ";
}
return finall;
}
My contains function checks to see the array contains a decimal
/**
* this function checks to see if a decimal is present in char array
* @param ch
* @param c
* @return
*/
public boolean contains(char[] ch, char c) {
for (char a : ch) {
if (a == c) {
return true;
}
}
return false;
}
My reverse function is simple it reverses the char array
public char[] reverse(char[] ch) {
char[] temp = new char[ch.length];
int cnt = 0;
for (int i = ch.length - 1; i >= 0; i--) {
temp[cnt++] = ch[i];
}
return temp;
}