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;
        }

 

posted @ 2020-08-20 17:47  戈博折刀  阅读(982)  评论(0编辑  收藏  举报