Java學習-047-數值格式化及小數位元四捨五入

來源:互聯網
上載者:User

標籤:

此小工具類主要用於數值四捨五入、數值格式化輸出,很簡單,若想深入研究,敬請自行查閱 BigDecimal 或 DecimalFormat 的 API,BigDecimal.setScale(位元,四捨五入法)中四捨五入法有如下 7 種:

         1、 ROUND_UP:遠離零方向舍入。向絕對值最大的方向舍入,只要捨棄位非0即進位。

         2、 ROUND_DOWN:趨向零方向舍入。向絕對值最小的方向輸入,所有的位都要捨棄,不存在進位情況。

         3、 ROUND_CEILING:向正無窮方向舍入。向正最大方向靠攏。若是正數,舍入行為類似於ROUND_UP,若為負數,舍入行為類似於ROUND_DOWN。Math.round()方法就是使用的此模式。

         4、 ROUND_FLOOR:向負無窮方向舍入。向負無窮方向靠攏。若是正數,舍入行為類似於ROUND_DOWN;若為負數,舍入行為類似於ROUND_UP。

         5、 HALF_UP:最近數字舍入(5進)。這是我們最經典的四捨五入。

         6、 HALF_DOWN:最近數字舍入(5舍)。在這裡5是要捨棄的。

         7、 HAIL_EVEN:銀行家舍入法。

 

不多說,直接上碼,如下所示:

  1 /**  2  * Aaron.ffp Inc.  3  * Copyright (c) 2004-2016 All Rights Reserved.  4  */  5 package cn.ffp.autotest.api.util;  6   7 import java.math.BigDecimal;  8 import java.math.RoundingMode;  9 import java.text.DecimalFormat; 10  11 import org.apache.log4j.Logger; 12 import org.apache.log4j.xml.DOMConfigurator; 13  14 import cn.ffp.autotest.api.settings.CONSINFO; 15  16 /** 17  * <strong>計算工具類</strong><br> 18  * <br> 19  * @author Aaron.ffp 20  * @version V1.0.0: autotest-api cn.ffp.autotest.api.util MathUtil.java, 2016-04-12 17:51:58.301 Exp $ 21  */ 22 public class MathUtil { 23     private static Logger logger = Logger.getLogger(MathUtil.class.getName()); 24     private static String msg    = ""; 25      26     public MathUtil() { 27         DOMConfigurator.configure(CONSINFO.CONF_LOG4J_XML); 28     } 29      30     /** 31      * <strong>對數值進行格式化輸出</strong><br> 32      * <ul> 33      * <li>例如:format("2.23956", 3)的結果為:2.240</li> 34      * </ul> 35      * <br> 36      * @author Aaron.ffp 37      * @version V1.0.0: autotest-api cn.ffp.autotest.api.util MathUtil.java format, 2016-04-12 20:13:43.664 Exp $ 38      *  39      * @param digit 待格式化數值 40      * @param scale 保留位元(小於1時為整數) 41      * @return 格式化數字字串 42      */ 43     public static String format(double digit, int scale) { 44         String format = "#."; 45          46         if (scale < 1) { 47             format = "#"; 48         } 49          50         for (int i = 0; i < scale; i++) { 51             format += "0"; 52         } 53          54         return MathUtil.format(digit, format); 55     } 56      57     /** 58      * <strong>對數值進行格式化輸出</strong><br> 59      * <ul> 60      * <li>格式化樣式樣本(#.00,表示保留2位;#.0000,表示保留4位)</li> 61      * </ul> 62      * <br> 63      * @author Aaron.ffp 64      * @version V1.0.0: autotest-api cn.ffp.autotest.api.util MathUtil.java format, 2016-04-12 19:44:00.926 Exp $ 65      *  66      * @param digit 待格式化數值 67      * @param format 格式化樣式 68      * @return 格式化數值字串 69      */ 70     private static String format(double digit, String format) { 71         try { 72             DecimalFormat decimalFormat = new DecimalFormat(format); 73              74             return decimalFormat.format(digit); 75         } catch (NullPointerException npe) { 76             msg = "將數字【" + digit + "】依據樣式【" + format + "】格式化失敗,原因:"; 77             logger.error(msg, npe); 78              79             return null; 80         } catch (IllegalArgumentException iae) { 81             msg = "將數字【" + digit + "】依據樣式【" + format + "】格式化失敗,原因:"; 82             logger.error(msg, iae); 83              84             return null; 85         } 86     } 87      88     /** 89      * <strong>對數值進行四捨五入</strong><br> 90      * <ul> 91      * <li>採用銀行家舍入法</li> 92      * </ul> 93      * <br> 94      * @author Aaron.ffp 95      * @version V1.0.0: autotest-api cn.ffp.autotest.api.util MathUtil.java scale, 2016-04-12 19:42:52.068 Exp $ 96      *  97      * @param digit 數值 98      * @param scale 保留位元 99      * @return 四捨五入後的數值100      */101     public static String scale(String digit, int scale) {102         try {103             if (scale < 0) {104                 msg = "對【" + digit + "】進行四捨五入失敗,原因:指定位元【" + scale + "】不可小於0!請檢查!";105                 logger.warn(msg);106                 107                 return null;108             }109             110             return new BigDecimal(digit).setScale(scale, RoundingMode.HALF_EVEN).toString();111         } catch (NumberFormatException nfe) {112             msg = "擷取【" + digit + "】指定位元【" + scale + "】四捨五入失敗,原因:";113             logger.error(msg, nfe);114         } catch (ArithmeticException ae) {115             msg = "擷取【" + digit + "】指定位元【" + scale + "】四捨五入失敗,原因:";116             logger.error(msg, ae);117         }118         119         return null;120     }121 }

  

  對應測試源碼:

 1 package cn.ffp.autotest.api.util; 2  3 import org.testng.annotations.Test; 4  5 public class MathUtilTest { 6     @Test(description = "public static String format(double digit, int scale) --- 測試") 7     public void test_format() { 8         System.out.println("MathUtil.format(\"2.23956\", 3) \t " + MathUtil.format(2.23956, 3)); 9         System.out.println("MathUtil.format(\"2.23956\", 0) \t " + MathUtil.format(2.23956, 0));10         System.out.println("MathUtil.format(\"2.23956\", -34) \t " + MathUtil.format(2.23956, -34));11     }12 13     @Test(description = "public static String scale(String digit, int scale) --- 測試")14     public void test_scale() {15         System.out.println("MathUtil.scale(\"2.23956\", 3) \t " + MathUtil.scale("2.23956", 3));16         System.out.println("MathUtil.scale(\"2.23956\", 0) \t " + MathUtil.scale("2.23956", 0));17         System.out.println("MathUtil.scale(\"2.23956\", -3) \t " + MathUtil.scale("2.23956", -3));18     }19 }

 

至此, Java學習-047-數值格式化及小數位元四捨五入順利完結,希望此文能夠給初學 Java 的您一份參考。

最後,非常感謝親的駐足,希望此文能對親有所協助。熱烈歡迎親一起探討,共同進步。非常感謝! ^_^

 

Java學習-047-數值格式化及小數位元四捨五入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.