Java格式化輸出

來源:互聯網
上載者:User

在ACM上, 我們經常會碰到一些浮點數要求格式化輸出(即保留多少位小數等)

這裡主要介紹下Java怎麼方便的來對浮點數四捨五入的保留制定小數位元

首先, Java也有printf函數, 其作用跟C/C++的基本相似, 只是格式串不同.

下面就來介紹它們各自格式串的異同之處.

1。整數: 格式串都是%d

2。字元: 都是%c

3。字串:都是%s

4。浮點數(double/float):

C/C++中, 格式串為%lf/%f

Java中, 格式串為%f(沒有%lf)

 

在C/C++中, 如果我們想要保留到小數後2位輸出(四捨五入)可以這樣寫

double d1 = 123.635;<br />double d2 = 123.6;<br />printf("%0.2lf %.2lf/n", d1, d2);

//輸出為: 123.64 123.60

而在Java中呢, 

double d1 = 123.635;<br />double d2 = 123.6;<br />System.out.printf("%#.2f %#.2f/n", d1, d2);

//輸出為: 123.64 123.60

在Java中, float寫法同上.

 

 還有另一種方法, 就是使用java.text.DecimalFormat類

如:

double d1 = 123.635;<br />double d2 = 123.6;<br />DecimalFormat df = new DecimalFormat(".00");<br />System.out.println(df.format(d1) + " " + df.format(d2));

//輸出為: 123.64 123.60

聯繫我們

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