java自定義實現數值的四捨五入

java自定義實現數值的四捨五入


問題引入:html

   javaMath類提供的rint()和round()方法,提供了對數值進行舍入的處理,其方法以下:java

rint(double a)返回最接近參數並等於某一整數的double值。ide

round(double a)返回最接近參數的long
      round(float a)返回最接近參數的int
   可這三個方法並不能知足實際應用中的全部須要,所以須要自定義一個類實現四捨五入的功能。spa

           
public class RoundTool {
    //value 進行四捨五入的數值,dotNum 保留的小數位數
    public static String round(double value, int dotNum) {
        String strValue = String.valueOf(value);
        int pos = strValue.indexOf(".");    //小數點的位置
        int len = strValue.length();        //數值的總位數
        int dotLen = len - pos - 1;         //實際小數的位數
        String endNum = "";         //最後返回的字符串     
if (dotNum < dotLen) { // 須要保留的小數位數少於實際的小數位數,即小數有多
            String c = strValue.substring(pos + dotNum + 1, pos + dotNum + 2); // 得到保留小數位的下一位,對其進行四捨五入
            int cNum = Integer.parseInt(c); // 轉換爲整數
            double tempValue = Double.parseDouble(strValue); // 保留運算結果的中間變量
            if (cNum >= 5) { // cNum>=5,進位處理(保留小數位的最後一位加1),若保留兩位,則加上0.01
                String tempDot = "";
                for (int i = 0; i < dotNum - 1; i++) {
                    tempDot = tempDot + "0";
                }
                tempDot = "0." + tempDot + "1"; // 須要進位的小數值
                tempValue = tempValue + Double.parseDouble(tempDot);
                strValue = String.valueOf(tempValue); // 進位後的值轉換爲字符串
                endNum = strValue.substring(0, strValue.indexOf(".") + dotNum + 1);
            } else { // cNum<5,直接截取
                endNum = strValue.substring(0, strValue.indexOf(".") + dotNum + 1);
            }
        } else if (dotNum == dotLen) { // 須要保留的小數位數與實際的小數位數相等
            endNum = String.valueOf(value);
        } else { // 須要保留的小數位數大於實際的小數位數相等
            for (int i = 0; i <= dotNum - dotLen - 1; i++) {
                strValue = strValue + "0"; // 補「0」
            }
            endNum = strValue; // 最終的值
        }
        return endNum;
    }
    public static void main(String[] args) {
        System.out.println("數值123.121保留兩位小數:\t" + RoundTool.round(123.121, 2));
        System.out.println("數值123.456789保留3位小數:\t" + RoundTool.round(123.456789, 3));
        System.out.println("數值123.1231保留3位小數:\t" + RoundTool.round(123.1231, 3));
        System.out.println("數值123.5保留3位小數:\t" + RoundTool.round(123.5, 3));
    }
}

       

相關文章
相關標籤/搜索