Java:對double值進行四捨五入,保留兩位小數的幾種方法

來源:互聯網
上載者:User

標籤:小數   ase   ram   zha   round   格式化   java   text   dig   

1. 功能

將程式中的double值精確到小數點後兩位。可以四捨五入,也可以直接截斷。

比如:輸入12345.6789,輸出可以是12345.68也可以是12345.67。至於是否需要四捨五入,可以通過參數來決定(RoundingMode.UP/RoundingMode.DOWN等參數)。

2. 實現代碼
package com.clzhang.sample;import java.math.BigDecimal;import java.math.RoundingMode;import java.text.DecimalFormat;import java.text.NumberFormat;public class DoubleTest {        /**     * 保留兩位小數,四捨五入的一個老土的方法     * @param d     * @return     */    public static double formatDouble1(double d) {        return (double)Math.round(d*100)/100;    }
/** * The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. * @param d * @return */ public static double formatDouble2(double d) { // 舊方法,已經不再推薦使用// BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
// 新方法,如果不需要四捨五入,可以使用RoundingMode.DOWN BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP);
return bg.doubleValue(); } /** * NumberFormat is the abstract base class for all number formats. * This class provides the interface for formatting and parsing numbers. * @param d * @return */ public static String formatDouble3(double d) { NumberFormat nf = NumberFormat.getNumberInstance();
// 保留兩位小數 nf.setMaximumFractionDigits(2);
// 如果不需要四捨五入,可以使用RoundingMode.DOWN nf.setRoundingMode(RoundingMode.UP);
return nf.format(d); }
/** * 這個方法挺簡單的。 * DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. * @param d * @return */ public static String formatDouble4(double d) { DecimalFormat df = new DecimalFormat("#.00");
return df.format(d); }
/** * 如果只是用於程式中的格式化數值然後輸出,那麼這個方法還是挺方便的。 * 應該是這樣使用:System.out.println(String.format("%.2f", d)); * @param d * @return */ public static String formatDouble5(double d) { return String.format("%.2f", d); } public static void main(String[] args) { double d = 12345.67890; System.out.println(formatDouble1(d)); System.out.println(formatDouble2(d)); System.out.println(formatDouble3(d)); System.out.println(formatDouble4(d)); System.out.println(formatDouble5(d)); }}
3. 輸出

12345.68
12345.68
12,345.68
12345.68
12345.68

在法語環境下,除了前兩種方法顯示正常之外,後邊三種方法會將小數點顯示成逗號,如果做國際化要注意

Java:對double值進行四捨五入,保留兩位小數的幾種方法

聯繫我們

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