Java 中使用本地数字格式化程序的双值对齐

Double Value Aligment Using Local Number Formatter in Java

我正在从 java 创建一个应用来打印销售支票:

Locale locale = new Locale("EN", "US");
NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);

final private String contentTicket = "\n"
            + "_________________________________________\n"
            + "TOTAL:                      " + formatter.format(total) + "\n"
            + "PAY WITH:                   " + formatter.format(payWith) + "\n"
            + "CHANGE:                     " + formatter.format(change) + "\n"
            + "_________________________________________\n"
            + "      Thank you, have a good day...!!\n"
            + "=========================================\n";

我遇到的问题是当我对货币值使用 语言环境格式化程序 时对齐。 例如我希望输出结果是这样的:

    _________________________________________
    TOTAL:                       ,000.00
    PAY WITH:                   ,000.00
    CHANGE:                      ,000.00
    _________________________________________
          Thank you, have a good day...!!
    =========================================

但是,我明白了:

    _________________________________________
    TOTAL:                      ,000.00
    PAY WITH:                   ,000.00
    CHANGE:                     ,000.00
    _________________________________________
          Thank you, have a good day...!!
    =========================================

变量 totalpayWithchange 都是 Double 值。

提前致谢...

根据右对齐显示,这对我来说似乎没问题,其余字符串可以根据需要进行调制。试试这个:

public static void main(String[] args) {
            double total = 5000;
            double payWith = 10000;
            double change = 5000;
            Locale locale = new Locale("EN", "US");
            NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
            System.out.println("-----------------------------------------");
            System.out.println("TOTAL:\t\t\t" + formatAlignToRight(formatter.format(total)));
            System.out.println("PAY WITH:\t\t" + formatAlignToRight(formatter.format(payWith)));
            System.out.println("CHANGE:\t\t\t" + formatAlignToRight(formatter.format(change)));
            System.out.println("-----------------------------------------");
            System.out.println("      Thank you, have a good day...!!");
            System.out.println("=========================================");
        }

// 将打印流从 Redirect console output to string in java

转换为字符串
public static String formatAlignToRight(String x){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        PrintStream old = System.out;
        System.setOut(ps);
        System.out.printf("%20s",x); //This is right aligning for 20 characters
        System.out.flush();
        System.setOut(old);
        return baos.toString();
    }

Hint : You can't simply use another S.out within one for the required formatting.