Java DecimalFormat使用方法

来源:互联网 发布:淘宝一分钱试用电信卡 编辑:程序博客网 时间:2024/05/30 23:00
  1. import java.text.*;  
  2. import java.util.*; //后面要用到Locale类  
  3.  
  4. publicclass DecimalFormatSample {  
  5. publicstaticvoid main(String args[]) {  
  6.   DecimalFormat myformat1 = new DecimalFormat("###,###.0000");//使用系统默认的格式 
  7.   System.out.println(myformat1.format(111111123456.12));  
  8.  
  9.   Locale.setDefault(Locale.US);  
  10.   DecimalFormat myformat2 = new DecimalFormat("###,###.0000");//使用美国的格式 
  11.   System.out.println(myformat2.format(111111123456.12));  
  12.  
  13.   //----------------------------also use applypattern------------------------------// 
  14.  
  15.   DecimalFormat myformat3 = new DecimalFormat();  
  16.   myformat3.applyPattern("##,###.000");  
  17.   System.out.println(myformat3.format(11112345.12345));  
  18. //-----------------控制指数输出-------------------------------------------------// 
  19.  
  20.      DecimalFormat myformat4 = new DecimalFormat();  
  21.   myformat4.applyPattern("0.000E0000");  
  22.   System.out.println(myformat4.format(10000));  
  23.   System.out.println(myformat4.format(12345678.345));  
  24. //------------------百分数的输出-------------------------------------------// 
  25. /*     DecimalFormat是NumberFormat的一个子类,其实例被指定为特定的地区。因此,你可以使用NumberFormat.getInstance 指定一个地区,
  26. 然后将结构强制转换为一个DecimalFormat对象。文档中提到这个技术可以在大多情况下适用,但是你需要用try/catch 块包围强制转换以防转
  27. 换不能正常工作 (大概在非常不明显得情况下使用一个奇异的地区)。    */ 
  28.        DecimalFormat myformat5 = null;  
  29.   try{  
  30.       myformat5 = (DecimalFormat)NumberFormat.getPercentInstance();  
  31.   }catch(ClassCastException e)  
  32.   {  
  33.    System.err.println(e);   
  34.   }  
  35.   myformat5.applyPattern("00.0000%");  
  36.   System.out.println(myformat5.format(0.34567));  
  37.   System.out.println(myformat5.format(1.34567));       
  38. }  
  39.  
  40. /*---------------------------------运行结果---------------------------------------
  41. D:\google>java DecimalFormatSample
  42. 111,111,123,456.1200
  43. 111,111,123,456.1200
  44. 11,112,345.123
  45. 1.000E0004
  46. 1.235E0007
  47. 34.5670%
  48. 134.5670%
  49. */ 

 

 

转载自:http://newleague.iteye.com/blog/923966

原创粉丝点击