Java:print double - println或printf

时间:2015-12-03 10:34:54

标签: java printf println

假设我有以下代码:

double median = med(10.0, 12.0, 3.0); //method returns middle number as double

现在,我想写一条说明中位数的消息。可以使用 println()完成此操作,如下所示:

System.out.println("Your number was " + median);

或者我必须使用带有双倍值的 printf()吗?

我问的原因是因为我在网上看到了这两种做法1,但是当我尝试使用 println()时,我收到错误,除非我写信:

System.out.println(median);

因此,您可以使用 println()打印出 double 值和字符串,还是必须使用 printf() 为此目的?

2 个答案:

答案 0 :(得分:4)

The printf method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:
The println() which can be confusing at times. (Although both can be used in almost all cases).

 double a = 10;
 double b = 20;

System.out.println("a: " + a + " b: " + b);// Tedious string concatenation.

System.out.printf("a: %f b: %f\n", a, b);// Output using string formatting.

Output:

a: 10.0 b: 20.0
a: 10,000000 b: 20,000000

答案 1 :(得分:0)

Personally I find string concatenation easer on the eyes and easer to maintain. The %blah gets lost in the string, errors in string concatenation is a compile time error and adding a new variable requires less thought. However I'm in the minority on this.

The pros in printf is that you don't need to construct a bunch of formatters, others find its format easer on the eyes and when using a printf like method provided by a logging framework the string building only happens if actually required.

double value = 0.5;
System.out.println("value: " + value);
System.out.printf("value: %f", value);

If you want to set a number of decimal places:

    double value = 0.5;
    // String concatenation 
    DecimalFormat df = new DecimalFormat("0.000");
    System.out.println("value: " + df.format(value));

    // printf
    System.out.printf("value: %.3f", value);