4

I am trying to format a string whereby the '$' stick close to the price.

For example:

Oranges     3     $3.00     $9.00

But what I currently have:

Oranges     3 $    3.00 $    9.00

This is my code: (Note: "price" and "total" are double datatype)

System.out.printf("%-25s %10s $%10s $%10s", item, quantity, price, total);

I want to have a gap in between every output but I can't find a way to get the result that I wanted. Is there any ways to solve this?

4

3 回答 3

1

尝试

System.out.printf("%-25s %10s %10s %10s", item, quantity, "$" + price, "$" + total);

输出

Oranges                            3       $3.0       $9.0

或者,最重要的是,使用格式化程序方法

    String format(double d) {
        return String.format("$%.2f", d);
    }
...
    System.out.printf("%-25s %10s %10s %10s", item, quantity, format(price), format(total));

输出

Oranges                            3      $3.00      $9.00
于 2013-01-27T08:39:57.647 回答
0

您可以将它们转换为字符串以进行输出吗?Double 类型可以调用 toString() 方法,根据此链接:

http://www.java2s.com/Code/Java/Language-Basics/Convertdoubletostring.htm

然后你可以在每个字符串的顶部输出一个美元符号(如果你将它们加载到一个数组中,你甚至可以循环遍历所有字符串,并为所有字符串添加一个美元符号)。

这可能不是最好的选择,但我相信它会起作用。

于 2013-01-27T08:31:58.850 回答
0

去掉价格和总数上的 10 个空格填充。

System.out.printf("%-25s %10s $%s $%s", item, quantity, price, total);
于 2013-01-27T08:29:57.797 回答