java中 DecimalFormat類

來源:互聯網
上載者:User

標籤:span   start   net   格式   keyword   replace   dma   表示   tle   

我們經常要將數字進行格式化,比如取2位小數,這是最常見的。Java 提供 DecimalFormat 類,幫你用最快的速度將數字格式化為你需要的樣子。下面是一個例子:

  1. importjava.text.DecimalFormat;  
  2.     
  3. publicclassTestNumberFormat{  
  4.     
  5.   publicstaticvoidmain(String[]args){  
  6.     doublepi=3.1415927; //圓周率  
  7.     //取一位整數  
  8.     System.out.println(newDecimalFormat("0").format(pi));   //3  
  9.     //取一位整數和兩位小數  
  10.     System.out.println(newDecimalFormat("0.00").format(pi)); //3.14  
  11.     //取兩位整數和三位小數,整數不足部分以0填補。  
  12.     System.out.println(new DecimalFormat("00.000").format(pi));// 03.142  
  13.     //取所有整數部分  
  14.     System.out.println(newDecimalFormat("#").format(pi));   //3  
  15.     //以百分比方式計數,並取兩位小數  
  16.     System.out.println(new DecimalFormat("#.##%").format(pi)); //314.16%  
  17.     
  18.     longc=299792458;  //光速  
  19.     //顯示為科學計數法,並取五位小數  
  20.     System.out.println(newDecimalFormat("#.#####E0").format(c)); //2.99792E8  
  21.     //顯示為兩位整數的科學計數法,並取四位小數  
  22.     System.out.println(newDecimalFormat("00.####E0").format(c)); //29.9792E7  
  23.     //每三位以逗號進行分隔。  
  24.     System.out.println(newDecimalFormat(",###").format(c));   //299,792,458  
  25.     //將格式嵌入文本  
  26.     System.out.println(newDecimalFormat("光速大小為每秒,###米。").format(c));  
  27.   }  
  28. }  
  29. DecimalFormat 類主要靠 # 和 0 兩種預留位置號來指定數字長度。0 表示如果位元不足則以 0 填充,# 表示只要有可能就把數字拉上這個位置。上面的例子包含了差不多所有的基本用法,如果你想瞭解更多,請參考 DecimalFormat 類的文檔。

java中 DecimalFormat類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.