首页 > 解决方案 > 如何打印最后带有数字的语句,但将数字从右到左设置为一定长度?

问题描述

我对编码很陌生,除了简单的格式和布尔语句之外,我什么都不知道。我要打印的是:

Gross Pay:     $   0.00

我的代码是:

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

输出是

Gross Pay:     $0.00

我相信我想以 7 个空格长度从右到左打印。我该怎么做?

编辑:对不起,我没有更具体。我没有必要问它是否有效,但我问的是如何让它Gross Pay: $ 0.00与空间和所有东西完全一致。我的实际问题是如何获得$ 0.00$ 和 0.00 之间的空间 3 是自动的,而不是仅仅做+ " " + .

标签: javaprintf

解决方案


像这样的东西应该可以工作(已编辑):

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

样本输出:

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

推荐阅读