Java中printf的双%格式问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3853185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Double % formatting question for printf in Java
提问by D. Spigle
%s
is a string in printf
, and %d is a decimal I thought...yet when putting in
%s
是一个字符串printf
,而 %d 是我认为的小数......但在放入时
writer.printf("%d dollars is the balance of %s\r\n", bal, nm);
..an exception is thrown telling me that %d
!= lang.double. Ideas?
.. 抛出异常告诉我%d
!= lang.double。想法?
采纳答案by codaddict
%d
is for integers use %f
instead, it works for both float
and double
types:
%d
用于整数%f
,它适用于float
和double
类型:
double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000
回答by Adeel Ansari
Yes, %d
means decimal, but it means decimal number system, not decimal point.
是的,%d
表示十进制,但表示十进制数制,而不是小数点。
Further, as a complement to the former post, you can also control the number of decimal points to show. Try this,
此外,作为对前一篇文章的补充,您还可以控制显示的小数点数。尝试这个,
System.out.printf("%.2f %.1f",d,f); // prints 1.20 1.2
For more please refer to the API docs.
有关更多信息,请参阅API 文档。
回答by Andy
Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:
是的,%d 是十进制(整数),double 期望 %f。但简单地使用 %f 将默认为高达 6 的精度。要打印双精度数的所有精度数字,您可以通过字符串将其传递为:
System.out.printf("%s \r\n",String.valueOf(d));
or
或者
System.out.printf("%s \r\n",Double.toString(d));
This is what println do by default:
这是 println 默认所做的:
System.out.println(d)
(and terminates the line)
(并终止该行)
回答by Salazar
Following is the list of conversion characters that you may use in the printf:
以下是您可以在 printf 中使用的转换字符列表:
%d – for signed decimal integer
%f – for the floating point
%o – octal number
%c – for a character
%s – a string
%i – use for integer base 10
%u – for unsigned decimal number
%x – hexadecimal number
%% – for writing % (percentage)
%n – for new line = \n