简体   繁体   English

Double printf Java帮助

[英]Double printf java help

May someone explain to me how printf works with double. 可能有人向我解释printf如何与double一起工作。

I tried this sample of code 我尝试了这段代码示例

double d = 12345.123456789;

System.out.printf("START%13fEND %n", d);

And the output is: 输出为:

START 12345.123457END

I understand that it takes up 13 spaces the double d in this part. 我知道这部分占了Double d的13个空格。

But when I do the next piece of code: 但是,当我执行下一段代码时:

System.out.printf("START%fEND %n", d);

It outputs: 它输出:

START12345.123457END

Since %f is 6.2f why is it not: 由于%f6.2f为什么不是:

START 12345.13END

Use this: 用这个:

double d = 12345.123456789;

System.out.printf("START%.13fEND %n", d);

instead System.out.printf("START%13fEND %n", d); 而是System.out.printf("START%13fEND %n", d);

Since %f is 6.2f why is it not: 由于%f为6.2f,为什么不是:

START 12345.13END 开始12345.13END

If a decimal place is not specified ( %f ), the default is six digits to the right of the decimal. 如果未指定小数位( %f ),则默认值为小数点右边的六位数。 The numbers in in front of the decimal will always be respected. 小数点前的数字将始终受到尊重。

The 13 you orignally had %13f deals with the total number of character in the whole output. 您最初拥有%13f13字符处理整个输出中的字符总数。

START 12345.123457END 开始12345.123457END

When dealing with floats, the important number you want to consider, is the number behind the decimal. 处理浮点数时,要考虑的重要数字是小数点后的数字。 %.2f%


So the main two points to remember is that the number before the . 因此,要记住的主要两点是之前的数字. is the number of character spaces allocated, and the number after the . 是分配的字符空间的数量,以及.之后的数字. is the number of decimal places. 是小数位数。

Also keep in mind though, if the number of character spaces allocated is below the number of characters, all character will still show. 但也要记住,如果分配的字符空间数少于字符数,所有字符仍将显示。

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

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