1 package test; 2 3 import java.text.DecimalFormat; 4 5 public class DecimalFormatSimpleDemo { 6 7 //使用實例化對象設置格式化模式 8 static public void SingleFormat(String pattern,double value){ 9 //實例化DecimalFormat對象 10 DecimalFormat myFormat = new DecimalFormat(pattern); 11 String output = myFormat.format(value); 12 System.out.println(value+" "+pattern+" "+output); 13 } 14 //使用applyFormat()方法對數字進行格式化 15 static public void UseApplyFormatMethodFormat(String pattern,double value){ 16 DecimalFormat myFormat = new DecimalFormat();//實例化DecimalFormat對象 17 myFormat.applyPattern(pattern); 18 System.out.println(value+" "+pattern+" "+myFormat.format(value)); 19 } 20 21 public static void main(String[] args) { 22 SingleFormat("###,###.###",123456.789);//調用靜態SingleFormat()方法 23 SingleFormat("00000000.###kg",123456.789);//在數字後面加上單位 24 //按照格式模板格式化數字,不存在的位以0顯示 25 SingleFormat("000000.000", 123.78); 26 //調用靜態UseApplyFormatMethodFormat()方法 27 UseApplyFormatMethodFormat("###.##%", 0.789);//將數字轉換成百分數形式 28 //將小數點後格式化爲兩位 29 UseApplyFormatMethodFormat("###.##", 123456.789); 30 //將數字轉化爲千分數形式 31 UseApplyFormatMethodFormat("0.00\u2030", 0.789); 32 33 } 34 35 36 37 }
package test; import java.text.DecimalFormat; public class DecimalMethod { public static void main(String[] args) { DecimalFormat myFormat = new DecimalFormat(); myFormat.setGroupingSize(2);//將數字以每兩個數字分組(整數部分) String output = myFormat.format(123456.789); System.out.println("將數字以每兩個數字分組:"+output); myFormat.setGroupingUsed(false);//設置不容許數字進行分組 String output2 = myFormat.format(123456.789); System.out.println("不容許數字分組"+output2); } }