繁体   English   中英

将大十进制格式转换为美元格式的最佳方法是什么?

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

我有一个丑陋的打印方法,需要长的正则表达式作为字符串。 必须有一个更简单的解决方案。

// 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"))));

数字格式会保持我的Big Decimal精度吗? 实际的printf方法如下。

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");
    }
}

我知道这太可怕了。 有人在想更好的方法吗?

您可以使用NumberFormat#getCurrencyInstance(Locale)来格式化BigDecimal货币。 以下是使用USD格式的示例(使用美国语言环境):

BigDecimal amount = new BigDecimal("2.5");
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
String amountInDollarForm = formatter.format(amount);
System.out.println(amountInDollarForm); // prints $2.50

有关更多信息,请访问java.text.NumberFormat文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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