I'd be very glad to be proved wrong, but Java's printf-style formatting can't cope with right-justification of floats and providing the currency symbol. If you know otherwise, please let me know in a comment below. In the meantime, I'm using the workaround below. The code is HERE
import java.text.*;
import java.util.*;
public class Money {
/**
* This is just to demonstrate some
* right-justified currency formatting
*
*/
public static void main(String[] args) {
Object[][] DATA = {
{ "Text", 4523423.00 },
{ "Link", 656.98 },
{ "Another", 634.75 }
};
for(int i = 0;i < DATA.length;i++) {
System.out.printf("%-16s%s\n", DATA[i][0], Money.formatCurrency((Double)DATA[i][1], "%24.2f"));
}
}
/**
*
* @param d The currency amount
* @param formatString A formatting String (see <a href="http://java.sun.com/javase/6/docs/api/java/util/Formatter.html" title="class in java.util"><code>Formatter</code></a>) e.g. "%8.2f"
*
* @return A right-justifed currency String, preceded by the currency
* symbol of the default Locale
*/
public static String formatCurrency(double d, String formatString) {
String currencySymbol = Currency.getInstance(Locale.getDefault())
.getSymbol();
StringBuilder sb = new StringBuilder(String.format(formatString, d));
int i;
for (i = 0; (i < sb.length()) && (sb.charAt(i) == ' '); i++) {
}
int j = i;
for(i = 0;i < currencySymbol.length();i++,j++) {
sb.setCharAt(j, currencySymbol.charAt(i));
}
return sb.toString();
}
}
import java.util.*;
public class Money {
/**
* This is just to demonstrate some
* right-justified currency formatting
*
*/
public static void main(String[] args) {
Object[][] DATA = {
{ "Text", 4523423.00 },
{ "Link", 656.98 },
{ "Another", 634.75 }
};
for(int i = 0;i < DATA.length;i++) {
System.out.printf("%-16s%s\n", DATA[i][0], Money.formatCurrency((Double)DATA[i][1], "%24.2f"));
}
}
/**
*
* @param d The currency amount
* @param formatString A formatting String (see <a href="http://java.sun.com/javase/6/docs/api/java/util/Formatter.html" title="class in java.util"><code>Formatter</code></a>) e.g. "%8.2f"
*
* @return A right-justifed currency String, preceded by the currency
* symbol of the default Locale
*/
public static String formatCurrency(double d, String formatString) {
String currencySymbol = Currency.getInstance(Locale.getDefault())
.getSymbol();
StringBuilder sb = new StringBuilder(String.format(formatString, d));
int i;
for (i = 0; (i < sb.length()) && (sb.charAt(i) == ' '); i++) {
}
int j = i;
for(i = 0;i < currencySymbol.length();i++,j++) {
sb.setCharAt(j, currencySymbol.charAt(i));
}
return sb.toString();
}
}