I have an ugly print method that takes a long regex as a String. There has to be a simpler solution.
// output is in dollars
String formatString = "%1$-20d%2$-20.2f%3$-20.2f%4$.2f,%5$.2f,%6$.2f\n";
printf(formatString, paymentNumber++, BigDecimal.ZERO, BigDecimal.ZERO,
(amountBorrowed.divide(new BigDecimal("100"))),
(totalPayments.divide(new BigDecimal("100"))),
(totalInterestPaid.divide(new BigDecimal("100"))));
Is the number format going to keep my Big Decimal precision? The actual printf method is below.
private static void printf(String formatString, Object... args) {
try {
if (console != null) {
console.printf(formatString, args);
} else {
System.out.print(String.format(formatString, args));
}
} catch (IllegalFormatException e) {
System.out.print("Error printing...\n");
}
}
I know this is horrific. Anyone think of a better way?
You can use NumberFormat#getCurrencyInstance(Locale)
in order to format currency for BigDecimal
. Here is an example for formatting in USD (Using the US locale):
BigDecimal amount = new BigDecimal("2.5");
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
String amountInDollarForm = formatter.format(amount);
System.out.println(amountInDollarForm); // prints $2.50
For more information, pay a visit to the java.text.NumberFormat documentation.