保留幾位有效數字 多種方法實現及注意事項

  1. 保留兩位小數的幾種方式:  
  2.    
  3. 方式一:  
  4. 四捨五入   
  5. [java] view plaincopyprint?  
  6. double   f   =   111231.5585;     
  7. BigDecimal   b   =   new   BigDecimal(f);     
  8. double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();   
  9. 保留兩位小數。  
  10. 注意該方法整數時不能有效保留兩位小數,如:整數10,用上述方法只能得到10.0。(yongheng_123轉載時添加)
  11.    
  12. 方式二:  
  13. java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");   
  14. df.format(你要格式化的數字);  
  15. 例:new java.text.DecimalFormat("#.00").format(3.1415926)  
  16. #.00 表示兩位小數 #.0000四位小數 以此類推...  
  17. 注意:該方法當數字爲0時保留兩位小數輸出結果是.00,而不是0.00,需要單獨處理。(yongheng_123轉載時添加) 
  18. 方式三:  
  19. double d = 3.1415926;  
  20. String result = String .format("%.2f");  
  21. %.2f %. 表示 小數點前任意位數   2 表示兩位小數格式後的結果爲f 表示浮點型  
  22.  
  23. 方式四:  
  24. NumberFormat ddf1=NumberFormat.getNumberInstance() ;  
  25. void setMaximumFractionDigits(int digits)  
  26. digits 顯示的數字位數  
  27. 爲格式化對象設定小數點後的顯示的最多位,顯示的最後位是舍入的  
  28. [java] view plaincopyprint?  
  29. import java.text.* ;    
  30. import java.math.* ;    
  31. class TT{    
  32.  public static void main(String args[]){     
  33.   double x=23.5455;    
  34.   NumberFormat ddf1=NumberFormat.getNumberInstance() ;    
  35.     
  36.   ddf1.setMaximumFractionDigits(2);    
  37.   String s= ddf1.format(x) ;    
  38.   System.out.print(s);    
  39.  }    
  40. }    
  41.     
  42. ---------------------------------------------------------------------------------------------------------  
  43.    
  44. 有一篇:  
  45.    
  46. 1)、浮點數精確計算  
  47. 勝利油田三流合一項目中一直存在一個問題,就是每次報表統計的物資金額和實際的金額要差那麼幾分錢,和實際金額不一致,讓客戶覺得總是不那麼舒服,原因是因爲我們使用java的浮點類型double來定義物資金額,並且在報表統計中我們經常要進行一些運算,但Java中浮點數(doublefloat)的計算是非精確計算,請看下面一個例子:  
  48.     System.out.println(0.05 + 0.01);  
  49.     System.out.println(1.0 - 0.42);  
  50.     System.out.println(4.015 * 100);  
  51.     System.out.println(123.3 / 100);  
  52. 你的期望輸出是什麼?可實際的輸出確實這樣的:  
  53.     0.060000000000000005  
  54. 0.5800000000000001  
  55. 401.49999999999994  
  56. 1.2329999999999999  
  57. 這個問題就非常嚴重了,如果你有123.3元要購買商品,而計算機卻認爲你只有123.29999999999999元,錢不夠,計算機拒絕交易。  
  58. 2)、四捨五入  
  59. 是否可以四捨五入呢?當然可以,習慣上我們本能就會這樣考慮,但四捨五入意味着誤差,商業運算中可能意味着錯誤,同時Java中也沒有提供保留指定位數的四捨五入方法,只提供了一個Math.round(double d)和Math.round(float f)的方法,分別返回長整型和整型值。round方法不能設置保留幾位小數,我們只能象這樣(保留兩位):  
  60. [java] view plaincopyprint?  
  61. public double round(double value){    
  62.   return Math.round( value * 100 ) / 100.0;    
  63. }    
  64.   
  65. 但非常不幸的是,上面的代碼並不能正常工作,給這個方法傳入4.015它將返回4.01而不是4.02,如我們在上面看到的  
  66. 4.015 * 100 = 401.49999999999994  
  67. 因此如果我們要做到精確的四捨五入,這種方法不能滿足我們的要求。  
  68. 還有一種方式是使用java.text.DecimalFormat,但也存在問題,format採用的舍入模式是ROUND_HALF_DOWN(舍入模式在下面有介紹),比如說4.025保留兩位小數會是4.02,因爲.025距離” nearest neighbor”(.02和.03)長度是相等,向下舍入就是.02,如果是4.0251那麼保留兩位小數就是4.03。  
  69. System.out.println(new java.text.DecimalFormat("0.00").format(4.025));  
  70. System.out.println(new java.text.DecimalFormat("0.00").format(4.0251));  
  71. 輸出是  
  72. 4.02  
  73. 4.03  
  74.    
  75. 3)、浮點數輸出(科學記數法)  
  76. Java浮點型數值在大於9999999.0就自動轉化爲科學記數法來表示,我們看下面的例子:  
  77.     System.out.println(999999999.04);  
  78.     System.out.println(99999999.04);  
  79.     System.out.println(10000000.01);  
  80.     System.out.println(9999999.04);  
  81. 輸出的結果如下:  
  82.     9.9999999904E8  
  83. 9.999999904E7  
  84. 1.000000001E7  
  85. 9999999.04  
  86.     但有時我們可能不需要科學記數法的表示方法,需要轉換爲字符串,還不能直接用toString()等方法轉換,很煩瑣。  
  87. BigDecimal介紹  
  88. BigDecimal是Java提供的一個不變的、任意精度的有符號十進制數對象。它提供了四個構造器,有兩個是用BigInteger構造,在這裏我們不關心,我們重點看用double和String構造的兩個構造器(有關BigInteger詳細介紹請查閱j2se API文檔)。  
  89. BigDecimal(double val)  
  90.           Translates a double into a BigDecimal.  
  91.    
  92. BigDecimal(String val)  
  93.           Translates the String representation of a BigDecimal into a BigDecimal.  
  94.    
  95.   
  96. BigDecimal(double)是把一個double類型十進制數構造爲一個BigDecimal對象實例。  
  97. BigDecimal(String)是把一個以String表示的BigDecimal對象構造爲BigDecimal對象實例。  
  98. 習慣上,對於浮點數我們都會定義爲doublefloat,但BigDecimal API文檔中對於BigDecimal(double)有這麼一段話:  
  99. Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .10000000000000000555111512312578 27021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances notwithstanding.  
  100. The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one  
  101. 下面對這段話做簡單解釋:  
  102. 注意:這個構造器的結果可能會有不可預知的結果。有人可能設想new BigDecimal(.1)等於.1是正確的,但它實際上是等於.1000000000000000055511151231257827021181583404541015625,這就是爲什麼.1不能用一個double精確表示的原因,因此,這個被放進構造器中的長值並不精確的等於.1,儘管外觀看起來是相等的。  
  103. 然而(String)構造器,則完全可預知的,new BigDecimal(“.1”)如同期望的那樣精確的等於.1,因此,(String)構造器是被優先推薦使用的。  
  104. 看下面的結果:  
  105.       System.out.println(new BigDecimal(123456789.02).toString());  
  106.       System.out.println(new BigDecimal("123456789.02").toString());  
  107. 輸出爲:  
  108. 123456789.01999999582767486572265625  
  109. 123456789.02  
  110. 現在我們知道,如果需要精確計算,非要用String來夠造BigDecimal不可!  
  111. 實現方案  
  112. 現在我們已經知道怎麼解決這個問題了,原則上是使用BigDecimal(String)構造器,我們建議,在商業應用開發中,涉及金額等浮點數計算的數據,全部定義爲String,數據庫中可定義爲字符型字段,在需要使用這些數據進行運算的時候,使用BigDecimal(String)構造BigDecimal對象進行運算,保證數據的精確計算。同時避免了科學記數法的出現。如果科學記數表示法在應用中不是一種負擔的話,可以考慮定義爲浮點類型。  
  113.    
  114. 這裏我們提供了一個工具類,定義浮點數的加、減、乘、除和四捨五入等運算方法。以供參考。  
  115. 源文件MathExtend.java:  
  116. [java] view plaincopyprint?  
  117. import java.math.BigDecimal;    
  118.     
  119. public class MathExtend    
  120.     
  121. {    
  122.     
  123.   //默認除法運算精度     
  124.     
  125.   private static final int DEFAULT_DIV_SCALE = 10;    
  126.     
  127.      
  128.     
  129.      
  130.     
  131.   public static double add(double v1, double v2)    
  132.     
  133.   {    
  134.     
  135.       BigDecimal b1 = new BigDecimal(Double.toString(v1));    
  136.     
  137.       BigDecimal b2 = new BigDecimal(Double.toString(v2));    
  138.     
  139.       return b1.add(b2).doubleValue();    
  140.     
  141.   }    
  142.     
  143.      
  144.     
  145.   public static String add(String v1, String v2)    
  146.     
  147.   {    
  148.     
  149.       BigDecimal b1 = new BigDecimal(v1);    
  150.     
  151.       BigDecimal b2 = new BigDecimal(v2);    
  152.     
  153.       return b1.add(b2).toString();    
  154.     
  155.   }    
  156.     
  157.      
  158.     
  159.      
  160.     
  161.   public static double subtract(double v1, double v2)    
  162.     
  163.   {    
  164.     
  165.       BigDecimal b1 = new BigDecimal(Double.toString(v1));    
  166.     
  167.       BigDecimal b2 = new BigDecimal(Double.toString(v2));    
  168.     
  169.       return b1.subtract(b2).doubleValue();    
  170.     
  171.   }    
  172.     
  173.      
  174.     
  175.      
  176.     
  177.   public static String subtract(String v1, String v2)    
  178.     
  179.   {    
  180.     
  181.       BigDecimal b1 = new BigDecimal(v1);    
  182.     
  183.       BigDecimal b2 = new BigDecimal(v2);    
  184.     
  185.       return b1.subtract(b2).toString();    
  186.     
  187.   }    
  188.     
  189.      
  190.     
  191.      
  192.     
  193.      
  194.     
  195.   public static double multiply(double v1, double v2)    
  196.     
  197.   {    
  198.     
  199.       BigDecimal b1 = new BigDecimal(Double.toString(v1));    
  200.     
  201.       BigDecimal b2 = new BigDecimal(Double.toString(v2));    
  202.     
  203.       return b1.multiply(b2).doubleValue();    
  204.     
  205.   }    
  206.     
  207.      
  208.     
  209.      
  210.     
  211.   public static String multiply(String v1, String v2)    
  212.     
  213.   {    
  214.     
  215.       BigDecimal b1 = new BigDecimal(v1);    
  216.     
  217.       BigDecimal b2 = new BigDecimal(v2);    
  218.     
  219.       return b1.multiply(b2).toString();    
  220.     
  221.   }    
  222.     
  223.      
  224.     
  225.      
  226.     
  227.   public static double divide(double v1, double v2)    
  228.     
  229.   {    
  230.     
  231.       return divide(v1, v2, DEFAULT_DIV_SCALE);    
  232.     
  233.   }    
  234.     
  235.      
  236.     
  237.      
  238.     
  239.   public static double divide(double v1,double v2, int scale)    
  240.     
  241.   {    
  242.     
  243.       return divide(v1, v2, scale, BigDecimal.ROUND_HALF_EVEN);    
  244.     
  245.   }    
  246.     
  247.      
  248.     
  249.      
  250.     
  251.   public static double divide(double v1,double v2,int scale, int round_mode){    
  252.     
  253.           if(scale < 0)    
  254.     
  255.           {    
  256.     
  257.               throw new IllegalArgumentException("The scale must be a positive integer or zero");    
  258.     
  259.           }    
  260.     
  261.           BigDecimal b1 = new BigDecimal(Double.toString(v1));    
  262.     
  263.           BigDecimal b2 = new BigDecimal(Double.toString(v2));    
  264.     
  265.           return b1.divide(b2, scale, round_mode).doubleValue();    
  266.     
  267.   }    
  268.     
  269.      
  270.     
  271.      
  272.     
  273.   public static String divide(String v1, String v2)    
  274.     
  275.   {    
  276.     
  277.       return divide(v1, v2, DEFAULT_DIV_SCALE);    
  278.     
  279.   }    
  280.     
  281.      
  282.     
  283.      
  284.     
  285.   public static String divide(String v1, String v2, int scale)    
  286.     
  287.   {    
  288.     
  289.       return divide(v1, v2, DEFAULT_DIV_SCALE, BigDecimal.ROUND_HALF_EVEN);    
  290.     
  291.   }    
  292.     
  293.      
  294.     
  295.      
  296.     
  297.   public static String divide(String v1, String v2, int scale, int round_mode)    
  298.     
  299.   {    
  300.     
  301.       if(scale < 0)    
  302.     
  303.       {    
  304.     
  305.           throw new IllegalArgumentException("The scale must be a positive integer or zero");    
  306.     
  307.       }    
  308.     
  309.       BigDecimal b1 = new BigDecimal(v1);    
  310.     
  311.       BigDecimal b2 = new BigDecimal(v2);    
  312.     
  313.       return b1.divide(b2, scale, round_mode).toString();    
  314.     
  315.   }    
  316.     
  317.      
  318.     
  319.      
  320.     
  321.   public static double round(double v,int scale)    
  322.     
  323.   {    
  324.     
  325.       return round(v, scale, BigDecimal.ROUND_HALF_EVEN);    
  326.     
  327.   }    
  328.     
  329.      
  330.     
  331.   public static double round(double v, int scale, int round_mode)    
  332.     
  333.   {    
  334.     
  335.      if(scale<0)    
  336.     
  337.      {    
  338.     
  339.          throw new IllegalArgumentException("The scale must be a positive integer or zero");    
  340.     
  341.      }    
  342.     
  343.      BigDecimal b = new BigDecimal(Double.toString(v));    
  344.     
  345.      return b.setScale(scale, round_mode).doubleValue();    
  346.     
  347.   }    
  348.     
  349.      
  350.     
  351.      
  352.     
  353.   public static String round(String v, int scale)    
  354.     
  355.   {    
  356.     
  357.     return round(v, scale, BigDecimal.ROUND_HALF_EVEN);    
  358.     
  359.   }    
  360.     
  361.      
  362.     
  363.   public static String round(String v, int scale, int round_mode)    
  364.     
  365.   {    
  366.     
  367.      if(scale<0)    
  368.     
  369.      {    
  370.     
  371.          throw new IllegalArgumentException("The scale must be a positive integer or zero");    
  372.     
  373.      }    
  374.     
  375.      BigDecimal b = new BigDecimal(v);    
  376.     
  377.      return b.setScale(scale, round_mode).toString();    
  378.   }    
  379. }    
  380.   
  381. BigDecimal 舍入模式(Rounding mode)介紹:  
  382. BigDecimal定義了一下舍入模式,只有在作除法運算或四捨五入時纔用到舍入模式,下面簡單介紹,詳細請查閱J2se API文檔  
  383. static int  
  384.  ROUND_CEILING  
  385.           Rounding mode to round towards positive infinity.  
  386. 向正無窮方向舍入  
  387.    
  388. static int  
  389.  ROUND_DOWN  
  390.           Rounding mode to round towards zero.  
  391. 向零方向舍入  
  392.    
  393. static int  
  394.  ROUND_FLOOR  
  395.           Rounding mode to round towards negative infinity.  
  396. 向負無窮方向舍入  
  397.    
  398. static int  
  399.  ROUND_HALF_DOWN  
  400.           Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.  
  401. 向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,向下舍入, 例如1.55 保留一位小數結果爲1.5  
  402.    
  403. static int  
  404.  ROUND_HALF_EVEN  
  405.           Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.  
  406. 向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,如果保留位數是奇數,使用ROUND_HALF_UP ,如果是偶數,使用ROUND_HALF_DOWN  
  407.    
  408. static int  
  409.  ROUND_HALF_UP  
  410.           Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.  
  411. 向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,向上舍入, 1.55保留一位小數結果爲1.6  
  412.    
  413. static int  
  414.  ROUND_UNNECESSARY  
  415.           Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.  
  416. 計算結果是精確的,不需要舍入模式  
  417.    
  418. static int  
  419.  ROUND_UP  
  420.           Rounding mode to round away from zero.  
  421. 向遠離0的方向舍入  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章