Java四捨五入時保留指定小數位數

方式一:

double f = 3.1516;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 
輸出結果f1爲 3.15;

源碼解讀:
  public BigDecimal setScale(int newScale, int roundingMode) //int newScale 爲小數點後保留的位數, int roundingMode 爲變量進行取捨的方式;
  BigDecimal.ROUND_HALF_UP 屬性含義爲爲四捨五入java

方式二:

String format = new DecimalFormat("#.0000").format(3.1415926);
System.out.println(format);
輸出結果爲 3.1416

解讀:
  #.00 表示兩位小數 #.0000四位小數 以此類推…git

方式三:

double num = 3.1415926;
String result = String.format("%.4f", num);
System.out.println(result);
輸出結果爲:3.1416

解讀:
  %.2f 中 %. 表示 小數點前任意位數 2 表示兩位小數 格式後的結果爲f 表示浮點型。spa

方式四:

double num = Math.round(5.2544555 * 100) * 0.01d;
System.out.println(num);
輸出結果爲:5.25

解讀:
  最後乘積的0.01d表示小數點後保留的位數(四捨五入),0.0001 爲小數點後保留4位,以此類推......code

方式五:

1. 功能

將程序中的double值精確到小數點後兩位。能夠四捨五入,也能夠直接截斷。
好比:輸入12345.6789,輸出能夠是12345.68也能夠是12345.67。至因而否須要四捨五入,能夠經過參數來決定(RoundingMode.UP/RoundingMode.DOWN等參數)。orm

2. 實現代碼

package com.clzhang.sample;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleTest {
    /** 保留兩位小數,四捨五入的一個老土的方法 */
    public static double formatDouble1(double d) {
        return (double)Math.round(d*100)/100;
    }
    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();
    }
    public static String formatDouble3(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();

        // 保留兩位小數
        nf.setMaximumFractionDigits(2); 
        // 若是不須要四捨五入,能夠使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.UP);
        return nf.format(d);
    }
    /**這個方法挺簡單的 */
    public static String formatDouble4(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(d);
    }
    /**若是隻是用於程序中的格式化數值而後輸出,那麼這個方法仍是挺方便的, 應該是這樣使用:System.out.println(String.format("%.2f", d));*/
    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.68blog

相關文章
相關標籤/搜索