java中printf的用法

來源:互聯網
上載者:User

標籤:十六   oid   ack   system   stat   說明   對齊   組成   空格   

目前printf支援以下格式: 
          %c        單個字元 
          %d        十進位整數 
          %f        十進位浮點數 
          %o        八位元 
          %s        字串 
          %u        無符號十進位數 
          %x        十六進位數 
          %%        輸出百分比符號% 

 

--------------------------------------------------------------------------------------------------------------------------

下面對組成格式說明的各項加以說明: 
①%:表示格式說明的起始符號,不可缺少。 
②-:有-表示靠左對齊輸出,如省略表示靠右對齊輸出。 
③0:有0表示指定空位填0,如省略表示指定空位不填。 
④m.n:m指域寬,即對應的輸出項在輸出裝置上所佔的字元數。N指精度。用於說明輸出的實型數的小數位元。為指定n時,隱含的精度為n=6位。 
⑤l或h:l對整型指long型,對實型指double型。h用於將整型的格式字元修正為short型。 

 

 

 1 package com.hone.test; 2  3 // "%"表示進行格式化輸出, "%"之後的內容為格式的定義。 4 public class Printf { 5     public static void main(String[] args) { 6         double d = 345.678; 7         String s = "hello World"; 8         int a = 123; 9         10                 //浮點型的輸出11         System.out.printf("%,d",a);            //格式化輸出資料,每三個資料加上一個,12         System.out.println();13         System.out.printf("%f", d);            // 345.67800014         System.out.println();15             //"9.2"中的9表示輸出的長度,2表示小數點後的位元。  345.678位元不夠前面不上空格16         System.out.printf("%9.3f", d);    17         System.out.println();18         System.out.printf("%+9.3f", d);            //"+"表示輸出的數帶加號或減號19         System.out.println();20         System.out.printf("%-9.3f", d);            //"-"表示輸出的數靠左對齊(預設為靠右對齊)21         System.out.println();22         System.out.printf("%+-9.3f",d);            //"+-"表示輸出的數帶加號或減號且靠左對齊23         System.out.println();24         25                 //整型的輸出26         System.out.printf("%d", a);                //"d"表示輸出十進位整數。27         System.out.println();28         System.out.printf("%04d", a);            //規定為4位,不夠左邊添加029         System.out.println();30         System.out.printf("%d%%", a);            //如果想輸出百分數,則連續用兩個  %%31         System.out.println();32         System.out.printf("%o", a);                //"o"表示輸出八進位整數。33         System.out.println();34         System.out.printf("%x", a);                //"x"表示輸出八進位整數。35         36         37         //字串的輸出38         System.out.println();39         System.out.printf("%s%n", s);                //輸出字串,其中 %n表示換行40         41         System.out.printf("輸出一個浮點數:%.3f,一個整數:%d,一個字串:%s",d,a,s);        //輸出多個變數42         43     }44 45 }

 

java中printf的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.