Double % formatting question for printf in Java

前端 未结 4 1332
死守一世寂寞
死守一世寂寞 2020-12-14 15:46

%s is a string in printf, and %d is a decimal I thought...yet when putting in

writer.printf(\"%d dollars is the balance of %s\\r\\         


        
相关标签:
4条回答
  • 2020-12-14 16:31

    Following is the list of conversion characters that you may use in the 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
    
    0 讨论(0)
  • 2020-12-14 16:34

    %d is for integers use %f instead, it works for both float and double types:

    double d = 1.2;
    float f = 1.2f;
    System.out.printf("%f %f",d,f); // prints 1.200000 1.200000
    
    0 讨论(0)
  • 2020-12-14 16:37

    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:

    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:

    System.out.println(d) 
    

    (and terminates the line)

    0 讨论(0)
  • 2020-12-14 16:41

    Yes, %d means decimal, but it means decimal number system, not decimal point.

    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.

    0 讨论(0)
提交回复
热议问题