保留2位小數,使用java.text.NumberFormat

來源:互聯網
上載者:User

[記錄] 1.保留小數

保留兩位小數,java方式,使用NumberFormat來實現,結果四捨五入

        double sourcePrice = 4940.20;// sourcePrice = 1514940.20        double reductionPrice = 0.1;        double price = sourcePrice - reductionPrice;        NumberFormat nf = NumberFormat.getNumberInstance();        // notice here        nf.setMaximumFractionDigits(2);        System.out.println(nf.format(price));

輸出結果:
(結果中看到是一位,其實是預設去掉了最後一位的0。
即4940.10,最終顯示4940.1;
如果計算結果是4940.00,那麼最終是4940;)

4,940.1

.

1,514,940.1 2.分隔字元

注意上面結果的分隔字元,千位分隔字元,百萬分隔字元,……),使用時會直接顯示出分隔字元,如果想去掉,則使用
nf.setGroupingUsed(false);

輸出結果則變成了(無分隔字元):

4940.1

.

1514940.1 3.其他方法實現

double number = 12345.5593;// 目標值
System.out.println("---計算-保留2位小數-BigDecimal----------四捨五入--------------");BigDecimal bigDecimal = new BigDecimal(number);double resNumber = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();System.out.println(resNumber);
System.out.println("---計算-保留2位小數-DecimalFormat--------四捨五入----------------");DecimalFormat decimalFormat = new DecimalFormat("#.00");System.out.println(decimalFormat.format(number));
System.out.println("---計算-保留2位小數-String.format--------四捨五入----------------");System.out.println(String.format("%.2f", number));

輸出結果:

12345.55

聯繫我們

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