简体   繁体   中英

What is the best way to format a big decimal into dollar form?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM