I need to format a number with space as thousand separator in my Java code for Android.
How can these functions be improved?
- What are the pros and cons to the first recursive method?
- What are the pros and cons to the second substring method?
Is there maybe an even better and easier way to solve the problem?
Java code for the recursive variant:
/**
* Format a (int) Number with Space as Thousand Separator
* Recursive variant
* @param number the Number to Format
* @return String the Formatted Number
* @since 1.0
*/
public static String intToThousandSpacedStringOS(int number) {
boolean positive = true;
String t = "";
if (number < 0) {
positive = false;
number = -number;
}
if (number > 999) {
t = intToThousandSpacedStringOS(number / 1000) + " ";
do {
number = number % 1000;
} while (number > 999);
t += String.format("%03d", number);
} else {
t = "" + number;
}
return positive ? t : "-" + t;
}
Java code for the substring variant:
/**
* Format a (int) Number with Space as Thousand Separator
* SubString variant
* @param number the Number to Format
* @return String the Formatted Number
* @since 1.0
*/
public static String intToThousandSpacedStringOS(int number) {
boolean positive = true;
String t;
String r = "";
int i = 1;
if (number < 0) {
positive = false;
number = -number;
}
t = "" + number;
while (t.length() > 3 * i) {
r = t.substring(t.length() - 3 * i > 3 ? t.length() - 3 * (i + 1) : 0, t.length() - 3 * i) + " " + r;
i++;
}
r += t.substring(t.length() - 3 > 0 ? t.length() - 3 : 0, t.length());
return positive ? r : "-" + r;
}
System.out.printf( "%,d\n", number);
? \$\endgroup\$String.format("%,d\n", number).toString();
would return 123,456 or 123.456 or something language specific, not 123 456 as I want. \$\endgroup\$DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setGroupingSeparator(' '); DecimalFormat df = new DecimalFormat("#,###", dfs); System.out.println(df.format(-1000));
\$\endgroup\$