String字符串類型轉數字進行計算及其他校驗


 

 

轉:

BigDecimal判斷兩值是否相等(轉載)

 

  //字符串相乘比較
    public static boolean multCompare(String s1,String s2,String sum) {
        BigDecimal b1 = new BigDecimal(s1);
        BigDecimal b2 = new BigDecimal(s2);
        BigDecimal bSum = new BigDecimal(sum);
        if(b1.multiply(b2).compareTo(bSum)==0){
            return true;
        }
        return false;
    }

 

其他校驗:

 //    校驗參數非空
    private  static String hasNullField(String[] checkFields, JSONObject jsonObject) {
        for (int i = 0; i <checkFields.length ; i++) {
            String checkField = checkFields[i];
            String field = jsonObject.getString(checkField);
            if (field==null || "null".equals(field) || "".equals(field) || "".equals(field.trim())){
                //返回異常的字段
                return "入參必填字段:"+checkField+" 為空";
            }
        }
        return null;
    }

    //生成新的發票請求號
    public static String genNewNo(String s) {
        //截取最后5位
        String s1 = s.substring(s.length() - 5);
        //隨機生成5位隨機數
        int s2 = (int) ((Math.random() * 9 + 1) * 10000);
        //替換
        String s3 = s.replace(s1, s2 + "");
        return s3;
    }

  /*** 判斷是否為合法 Double類型,可以用於錢幣 */
    public static boolean isDouble( String s ){
        Pattern pattern= Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判斷小數點后2位的數字的正則表達式
        Matcher match=pattern.matcher( s );
        boolean bo = match.matches();
        return bo;
    }

    public static String checkNum( Map<String, String> numMap){
        for (Map.Entry<String, String> entry : numMap.entrySet()) {
            String key = entry.getKey();
            try {
                String value = entry.getValue();
                if (!isDouble(value)){
                    return "入參字段:"+key+" 不是有效數字";
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "入參字段:"+key+" 不是有效數字";
            }
        }
        

   public static String checkCreate(JSONObject jsonObject){
        //數字校驗
        Map<String, String> numMap = new HashMap<>();
        //校驗最外層字段
        String[] mainFields = {
                "timestamp",
                "seqId",
                "invoiceInfo",
                "orderList"
        };
        String msg  = hasNullField(mainFields, jsonObject);
        if(msg!=null){
            return msg;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM