0

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?

user10297
  • 139
  • 4
  • 11
  • 3
    [getCurrencyInstance](http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)) – Anirban Nag 'tintinmj' Dec 17 '13 at 20:01
  • How would this be used to replace the above though? – user10297 Dec 17 '13 at 20:19
  • (1) A format string is not a "regex"; regular expressions are used for pattern matching. (2) Yes, this should work fine with `BigDecimal`. (3) If you have six numbers that you need to format in six different ways, you're going to need something like this. You could break it into six parts, call `String.format` on each one, and concatenate the results, and the result might be cleaner and more readable, but I wouldn't call it "simpler". YMMV. I'm not quite sure what you're hoping for. – ajb Dec 17 '13 at 20:20

1 Answers1

1

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.

Ben Barkay
  • 5,473
  • 2
  • 20
  • 29