網上摘來的,以后可能會用到
java開發中經常會有數字、貨幣金錢等格式化需求,貨幣保留幾位小數,貨幣前端需要加上貨幣符號等。可以用java.text.NumberFormat和java.text.DecimalFormat實現。
1 第一種:比如網上交易系統,數字保留4位小數: 2 public static void main(String[] args){ 3 NumberFormat nf = new DecimalFormat("##.####"); 4 Double d = 554545.4545454; 5 String str = nf.format(d); 6 System.out.println(str); 7 //輸出554545.4545 8 } 9 10 11 第二種:比如網上交易系統,金錢數字保留4位小數且以“¥”開頭: 12 public static void main(String[] args){ 13 NumberFormat nf = new DecimalFormat("$##.####"); 14 Double d = 554545.4545454; 15 String str = nf.format(d); 16 System.out.println(str); 17 //$554545.4545 18 } 19 20 21 第三種:比如網上交易系統,金錢數字保留4位小數且三位三位的隔開: 22 public static void main(String[] args){ 23 NumberFormat nf = new DecimalFormat("#,###.####"); 24 Double d = 554545.4545454; 25 String str = nf.format(d); 26 System.out.println(str); 27 //554,545.4544; 28 }
