繁体   English   中英

在Java中,有没有办法格式化double / int或非字符串变量的输出?

[英]In Java, is there a way to format the output of a double/int or non-string variable?

我意识到这听起来很简单,可能就是......把这个代码放在main()中,这是一个循环内部:

System.out.println(num[i]+"\t     "+qty[i]+"\t     "+money.format(price[i])+"\t"+money.format(value[i])+"\t"+reorder[i]);

在这里捕获的总数:

http://maradastudios.ucoz.com/school/Capture.png

你可能已经注意到,它工作正常。 但是,在输出期间,#114行(第2行到最后一行)的总值为$ 90.00。 这是正确的,但它会导致重新订购点变量出现奇数间距。 简单地说,我可以格式化这个变量以占用与更大的数字相同的空间吗?

就像是

String.format("%10.2f", yourFloat)
// or
System.out.format("%10.2f", yourFloat)

将打印一个10个字符宽(包括十进制)的字符串,小数点后面有两个数字字符。

文件

所以

String.format("$%6.2f", value[i])

将对齐$. 字符(除非value[i] > 999.99 )。


代替:

System.out.println(
    num[i]                +"\t     "+
    qty[i]                +"\t     "+
    money.format(price[i])+"\t"+
    money.format(value[i])+"\t"+
    reorder[i]);

(这正是你所拥有的,只是为了清晰而格式化并删除了滚动条)

我可能会写:

System.out.format("%5d\t %5d\t $%5.2f\t $%6.2f\t %5d %n", 
    num[i], qty[i], price[i], value[i], reorder[i]);

这假设pricevalue数组是浮点数或双精度数。 由于money不是标准类,除了添加$符号之外,很难确切知道它的作用。


字符串格式语法在文档中定义,但对于浮点数,它大致是

%X.Yf

其中X是总字段宽度, Y是小数点数

例如

"123.40"  Has a total width of 6:  
          3 + 1 [decimal point] + 2 = 6)
"  2.34"  Also has a total width of 6:
          2 [spaces] + 1 + 1 [decimal point] + 2 = 6
Formatter formatter = new Formatter();
    System.out.println(formatter.format("%20s %20s %20s %20s %20s", "Title*", "Title*", "Title*", "Title*", "Title*"));

    for (int i = 0; i < 10; i++) {
        formatter = new Formatter();

        System.out.println(formatter.format("%20s %20s %20s %20s %20s", num[i],qty[i],money.format(price[i]),money.format(value[i]),reorder[i]));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM