DecimalFormat能夠按照須要格式化數字,下面簡單介紹一下幾種使用。其中本身也踏踏實實踩了坑,謹此記錄。
保留位數設置
public class DecimalUtils { //保留2位,不足補0 private static final DecimalFormat df_fill_zero = new DecimalFormat("00.00"); //保留2位,不足保留原位數 private static final DecimalFormat df_fill_null = new DecimalFormat("##.##"); public static void main (String args[]) { System.out.println(df_fill_zero.format(1.2)); //01.20 不足2位補0 System.out.println(df_fill_null.format(1.2)); //1.2 不足2位保留原數位 System.out.println(df_fill_zero.format(1.224)); //01.22 超出2位截斷(舍入模式後面再說) System.out.println(df_fill_null.format(1.224)); //1.22 超出2位截斷(舍入模式後面再說) System.out.println(df_fill_zero.format(123.22)); //123.22 System.out.println(df_fill_null.format(123.22)); //123.22 } }
運行結果:spa
01.20 1.2 01.22 1.22 123.22 123.22
舍入模式code
默認舍入模式orm
public class FormatDefault { //保留3位,不足保留原位數 private static final DecimalFormat df_t = new DecimalFormat("#.###"); public static void main (String args[]) { //默認舍入模式(RoundingMode.HALF_EVEN) System.out.println(df_t.format(1234.2224)); //1234.222 System.out.println(df_t.format(1234.2226)); //1234.223 System.out.println(df_t.format(1234.2225)); //1234.223 最後一位偶數,舍入 System.out.println(df_t.format(1234.2235)); //1234.223 最後一位奇數,捨去 } }
四捨五入模式blog
public class FormatHalfUp { /*** * 最多保存3位小數,若是number少於3位則保留原小數位數,若是多於3位則四捨五入保留3位小數 */ public static String formatHalfUp(double number) { DecimalFormat df = new DecimalFormat("#.###"); df.setRoundingMode(RoundingMode.HALF_UP); return df.format(BigDecimal.valueOf(number)); //防止精度丟失,數字類型用BigDecimal } public static void main (String args[]) { //四捨五入舍入模式(RoundingMode.HALF_UP) System.out.println(formatHalfUp(1234.2224)); //1234.222 System.out.println(formatHalfUp(1234.2226)); //1234.223 System.out.println(formatHalfUp(1234.2225)); //1234.223 System.out.println(formatHalfUp(1234.2235)); //1234.224 } }