簡體   English   中英

我如何在末尾打印一個帶有數字的語句,但將數字從右到左設置為一定長度?

[英]How would I print a statement with a number at the end, but set the number from right to left at a certain lenght?

我對編碼很陌生,除了簡單的格式和 Boolean 聲明之外,我什么都不知道。 我要打印的是:

Gross Pay:     $   0.00

我的代碼是:

System.out.printf("Gross Pay:     " + "$" + "%.2f\n", grossPay);

output 是

Gross Pay:     $0.00

我相信我應該以 7 個空格長度從右到左打印。 我該怎么做?

編輯:對不起,我沒有更具體。 我沒有必要問它是否有效,但我問的是如何讓它准確地成為Gross Pay: $ 0.00以及空間和所有內容。 我的實際問題是如何獲得$ 0.00 ,讓 $ 和 0.00 之間的空間 3 是自動的,而不是只做+ " " +

這樣的事情應該有效(已編輯):

String.format("%7.2f", value)

樣本:

System.out.println("Gross Pay:     $" + String.format("%7.2f", 10.01));
System.out.println("Gross Pay:     $" + String.format("%7.2f", 100.01));
System.out.println("Gross Pay:     $" + String.format("%7.2f", 1000.01));
System.out.println("Gross Pay:     $" + String.format("%7.2f", 10000.01));

樣本 Output:

Gross Pay:     $  10.01
Gross Pay:     $ 100.01
Gross Pay:     $1000.01
Gross Pay:     $10000.01

作為使用空格的替代方法,這是一個帶有數字填充的示例:

        DecimalFormat currency = new DecimalFormat();
        currency.setGroupingUsed(false);
        currency.setMinimumIntegerDigits(12);
        currency.setMaximumIntegerDigits(12);
        currency.setMinimumFractionDigits(2);
        currency.setMaximumFractionDigits(2);
        currency.setDecimalSeparatorAlwaysShown(true);
        System.out.println("Gross Pay:     $" + currency.format(939394.02480240));

如果你這樣打印它可能是有效的:System.out.printf("Gross Pay: " + "$ " + "%.2f\n", grossPay);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM