gpt4 book ai didi

java - 在 Java 中使用本地数字格式化程序进行双值对齐

转载 作者:行者123 更新时间:2023-11-30 07:45:50 28 4
gpt4 key购买 nike

我正在使用 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: $5,000.00
PAY WITH: $10,000.00
CHANGE: $5,000.00
_________________________________________
Thank you, have a good day...!!
=========================================

但是,我得到了这个:

    _________________________________________
TOTAL: $5,000.00
PAY WITH: $10,000.00
CHANGE: $5,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.

关于java - 在 Java 中使用本地数字格式化程序进行双值对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33972058/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com