继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

非常实用的Java工具类,拿走不谢(三)

霜花似雪
关注TA
已关注
手记 163
粉丝 1.5万
获赞 8507

一、字符串工具类(StrUtil.java)

package com.lhf;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
/**
 * 字符串相关工具类
 *
 * @description 
 *
 * @author lhf
 * @createDate 2017年9月1日
 */
public final class StrUtil {
private StrUtil() {}
/**
* 用户名是否符合规范   ^[\u4E00-\u9FA5A-Za-z0-9]{6,16}$,支持中文、大小写字母、数字随意组合,默认长度6~16字符
* @return
*/
public static boolean isValidUsername(String username) {
System.out.println("输入的用户名不合法,6到20位");
return isValidUsername(username, 6, 20);
}
/**
* 用户名是否符合规范   ^[\u4E00-\u9FA5A-Za-z0-9]{6,16}$
* @param username
* @param min
* @param max
* @return
*/
public static boolean isValidUsername(String username,Integer min,Integer max) {
if (StringUtils.isBlank(username)) {
return false;
}
String reg = "^[\u4E00-\u9FA5A-Za-z0-9]{" + min + "," + max + "}$";
System.out.println("输入的用户名太短或太长");
return username.matches(reg);
}
/**
* 是否有效手机号码
* @param mobileNum
* @return
*/
public static boolean isMobileNum(String mobileNum) {
if (null == mobileNum) {
return false;
}
System.out.println(mobileNum.matches("^((13[0-9])|(14[4,7])|(15[^4,\\D])|(17[0-9])|(18[0-9]))(\\d{8})$"));
return mobileNum.matches("^((13[0-9])|(14[4,7])|(15[^4,\\D])|(17[0-9])|(18[0-9]))(\\d{8})$");
}
/**
* 是否有效邮箱
* @param email
* @return
*/
public static boolean isEmail(String email) {
if (null == email) {
return false;
}
System.out.println(email.matches("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$"));
return email.matches("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$");
}
/**
* 是否是QQ邮箱
*/
public static boolean isQQEmail(String email){
if(null == email)
return false;
System.out.println(email.matches("^[\\s\\S]*@qq.com$"));
return email.matches("^[\\s\\S]*@qq.com$");
}
/**
* 是否为16-22位银行账号
* @param bankAccount
* @return
*/
public static boolean isBankAccount(String bankAccount){
    if (null == bankAccount) {
            return false;
        }
    System.out.println(bankAccount.matches("^\\d{16,22}$"));
    return bankAccount.matches("^\\d{16,22}$");
}
/**
* 是否是纯数字,不含空格
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (StringUtils.isBlank(str)) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 是否数值类型,整数或小数
* @param number
* @return
*/
public static boolean isNumericalValue(String str) {
if (null == str) {
return false;
}
return str.matches("^[+-]?(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d)+)?$");
}
/**
* 是否整数(^[+-]?(([1-9]{1}\\d*)|([0]{1}))$)
*
* @param str
* @return
*
*/
public static boolean isNumericInt(String str) {
if (str == null) {
return false;
}
return str.matches("(^[+-]?([0-9]|([1-9][0-9]*))$)");
}
/**
* 是否正整数
* @param number
* @return
*/
public static boolean isNumericPositiveInt(String number) {
if (null == number) {
return false;
}
return number.matches("^[+-]?(([1-9]{1}\\d*)|([0]{1}))$");
}
/**
* 判断是否是正整数数或者一位小数
*
* @param str
* @return
*
*/
public static boolean isOneDouble(String str) {
//
if (str == null) {
return false;
}
return str.matches("^(\\d+\\.\\d{1,1}|\\d+)$");
}
/**
* 判断是否是正整数数或者一位小数
*
* @param str
* @return
*
*/
public static boolean isTwoDouble(String str) {
//
if (str == null) {
return false;
}
return str.matches("^(\\d+\\.\\d{1,2}|\\d+)$");
}
/**
* 判断给定字符串是否小于给定的值(min)
*
* @param str
* @param min
* @return
*/
public static boolean isNumLess(String str,float min) {
if (str == null) {
return false;
}
if (!isNumeric(str)) {
return false;
}
float val = Float.parseFloat(str);
return (val < min);
}
/**
* 判断给定的字符串大于说给定的值
*
* @param str
* @param max
* @return
*
*/
public static boolean isNumMore(String str,float max) {
if (str == null) {
return false;
}
if (!isNumeric(str)) {
return false;
}
float val = Float.parseFloat(str);
return (val > max);
}
/**
* 是否小数
*
* @param str
* @return
*
*/
public static boolean isNumericDouble(String str) {
if (str == null) {
return false;
}
return str.matches("^[+-]?(([1-9]\\d*\\.?\\d+)|(0{1}\\.\\d+)|0{1})");
}
/**
* 是否是16进制颜色值
*
* @param str
* @return
*
*/
public static boolean isColor(String str){
if (str == null) {
return false;
}
return str.matches("(^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$)");
}
/**
* 判断是否是Boolean值
*
* @param str
* @return
*
*/
public static boolean isBoolean(String str) {
if (str == null) {
return false;
}
return str.equals("true") || str.equals("false");
}
/**
* 判断是否是日期,格式:yyyy-MM-dd
*
* @param str
* @return
*
*/
public static boolean isDate(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
format.parse(str);
} catch (ParseException e) {
return false;
}
return true;
}
/**
* 判断是否是日期,格式:yyyy-MM-dd hh:mm:ss
*
* @param str
* @return
*
* @author huangyunsong
* @createDate 2015年12月8日
*/
public static boolean isDateyyyyMMddhhmmss(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
format.parse(str);
} catch (ParseException e) {
return false;
}
return true;
}
/**
* 使用map中的值替换str的指定内容
*
* @description 假设:date  supervisor设置SEO规则,date。其中date和supervisor是要被替换的内容,则map中key就为date,supervisor。
* 
* @param str
* @param map
* @return
*
*/
public static String replaceByMap(String str,Map<String,String> map){
String result = str;
if (map == null || map.isEmpty()) {
return result;
}
for (String _key : map.keySet()) {
result = result.replace(_key, map.get(_key));
}
return result;
}
/**
* 计算一个颜色值的的0.7透明度
*
* @param color 颜色值为ffffff/fff两种形式
* @return
*
*/
public static String colorByAlpha(String color){
if(color.length() == 3){
color = "000"+color;
}
String r = color.substring(0, 2);
String g = color.substring(2, 4);
String b = color.substring(4);
String nColor = Integer.toHexString(Integer.parseInt(r, 16)*7/10+255*3/10)+Integer.toHexString(Integer.parseInt(g, 16)*7/10+255*3/10)+Integer.toHexString(Integer.parseInt(b, 16)*7/10+255*3/10);
return nColor;
}
public static String[] toStr(int[] a){
List<String> list = new ArrayList<String>();
for(int i=0,max = a.length;i<max;i++){
list.add(a[i]+"");
if(i < max-1){
if(a[i]+1<a[i+1]){
list.add("...");
}
}
}
String[] strs = new String[list.size()];
list.toArray(strs);
return strs;
}
/**
* 脱敏处理
*
* @param str
* @param start
* @param end
* @param count
* @return
* @description 
*
* @author lhf
* @createDate 2018年7月13日
*/
public static String asterisk (String str, int start, int end, int count) {
StringBuffer result = new StringBuffer();
int length = str.length();
if (start <= length ) {
result.append(str.substring(0, start));
} else {
result.append(str.substring(0, length));
}
for (int i=0; i<count; i++) {
result.append("*");
}
if (end <= length ) {
result.append(str.substring(length-end, length));
} else {
result.append(str.substring(0, length));
}
       return result.toString();
}
/**
* 截取字符串
* @param oldStr 原字符串
* @param type 类型:1.平台用户名、2.用户真实姓名、3.用户身份证号码、4.用户手机号码、5.用户邮箱
* @return
*/
public static String cutOutStr(String oldStr, int type) {
String newStr = "";
int length = oldStr.length();
if (type == 1) {
if (length <= 3) {
newStr = oldStr.substring(0, oldStr.length() - 1) + "*";
} else if (length >= 4) {
newStr = oldStr.substring(0, 2) + copyStr("*", oldStr.length() - 3) + oldStr.substring(oldStr.length() - 1, oldStr.length());
} else {
newStr = oldStr;
}
System.out.println(newStr);
} else if (type == 2) {
if (length >= 2) {
newStr = oldStr.substring(0, 1) + copyStr("*", oldStr.length() - 1);
} else {
newStr = oldStr;
}
System.out.println(newStr);
} else if (type == 3) {
if (length == 18) {
newStr = oldStr.substring(0, 4) + copyStr("*", oldStr.length() - 6) + oldStr.substring(oldStr.length() - 2, oldStr.length());
} else {
newStr = oldStr;
}
System.out.println(newStr);
} else if (type == 4) {
System.out.println(newStr);
} else if (type == 5) {
System.out.println(newStr);
}
return newStr;
}
public static String copyStr(String str, int n) {
    String result = str;
    
    for (int i = 0; i < n - 1; i++) {
       result = result.concat(str);
    }
    
    return result;
}
public static void main(String[] args) {
//用户名是否符合规范
isValidUsername("刘豆豆123");
//isValidUsername("刘豆豆",1,3);
//是否有效手机号码
isMobileNum("18295514402");
//是否是有效邮箱
isEmail("ksjdhd@163.com");
//是否是QQ号码
isQQEmail("2782365hgfg");
//是否为16-22位银行账号
isBankAccount("6214668888952714400111111111");
//脱敏处理
String account= "6214668888952714400";
String accountStr = asterisk(account,4, 4,account.length() - 8);
System.out.println("银行卡脱敏处理后:" + accountStr);
//截取字符串
String Id = "130104197003231827";
String cutStr = cutOutStr(Id, 3);
System.out.println("截取字符串后:" + cutStr);
//利用commons-lang3包下的工具类,处理特殊字符
        String str = " <借款用途>:简介: &武汉&@汇聚力(商贸有限公司)是高端男装品牌M&C湖北省代理商。目前已在中山大洋百货,$世贸广场%上柜, 后期将陆续开@鲁广专柜,光谷大洋百货专柜和步行街形像店等。M&C男装品牌介绍:M&C,隶属于#苹果(中国)服装集团公司,M&C男装#品牌以原创\\个性\\时尚的品牌形象,崇尚以人性的真实,尊重作为生命存在的知性人群本身,充分展现了时尚简洁的男性世界,在时尚理念中彰显出优雅与高贵,让他变的更加的自信,卓而不群正是M&C所追求的。目前,公司经营情况良好,人员齐备,销售火热,计划在荆州、鄂州等地开设分店,因此需筹措分店建设的启动资金。";
String result = StringEscapeUtils.escapeHtml4(str);
System.out.println("result = " + result);
}
}

二、获取当前路径工具类(SystemPath.java)

package com.lhf;
/**
 * 得到当前应用的系统路径
 *
 * @description 
 *
 * @author lhf
 * @createDate 2017年9月12日
 */
public class SystemPath {
public static String getSysPath() {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").toString();
String temp = path.replaceFirst("file:/", "").replaceFirst(
"WEB-INF/classes/", "");
String separator = System.getProperty("file.separator");
String resultPath = temp.replaceAll("/", separator + separator);
return resultPath;
}
public static String getClassPath() {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").toString();
String temp = path.replaceFirst("file:/", "");
String separator = System.getProperty("file.separator");
String resultPath = temp.replaceAll("/", separator + separator);
return resultPath;
}
public static String getSystempPath() {
return System.getProperty("java.io.tmpdir");
}
public static String getSeparator() {
return System.getProperty("file.separator");
}
public static void main(String[] args) {
System.out.println(getSysPath());
System.out.println(System.getProperty("java.io.tmpdir"));
System.out.println(getSeparator());
System.out.println(getClassPath());
}
}

三、金额工具类(Trans2RMB.java)

package com.lhf;
/**
 * 金额工具类
 *
 * @description 
 *
 * @author lhf
 * @createDate 2018年7月13日
 */
public class Trans2RMB {  
  
    
      
    /** 
     * 从命令行接收一个数,在其中调用 checkNum() 方法对其进行 
     * 验证,并返回相应的值 
     * @return 如果输入合法,返回输入的这个数 
     */  
    public static String getNum(String loanmoney) {  
        
       
       
        // 判断用户输入是否合法  
        // 若合法,返回这个值;若非法返回 "0"  
        if(checkNum(loanmoney)) {  
            return loanmoney;  
        } else {  
            return "";  
        }  
    }  
      
    /** 
     * 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符 
     * @param s String 
     * @return 如果用户输入数据合法,返回 true,否则返回 false 
     */  
    private static boolean checkNum(String loanmoney) {  
        // 如果用户输入的数里有非数字字符,则视为非法数据,返回 false  
        try {  
            float f = Float.valueOf(loanmoney);  
            // 如果这个数小于零则视为非法数据,返回 false  
            if(f < 0) {  
                System.out.println("非法数据,请检查!");  
                return false;  
            }else {  
                return true;  
            }  
        } catch (NumberFormatException s) {  
            System.out.println("非法数据,请检查!");  
            return false;  
        }     
    }  
      
    /** 
     * 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法 
     * 进行相应的中文金额大写形式的转换 
     * 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的 
     * @param s String 
     * @return 转换好的中文金额大写形式的字符串 
     */  
    public static String splitNum(String loanmoney) {  
        // 如果传入的是空串则继续返回空串  
        if("".equals(loanmoney)) {  
            return "";  
        }  
        // 以小数点为界分割这个字符串  
        int index = loanmoney.indexOf(".");  
        // 截取并转换这个数的整数部分  
        String intOnly = loanmoney.substring(0, index);  
        String part1 = numFormat(1, intOnly);  
        // 截取并转换这个数的小数部分  
        String smallOnly = loanmoney.substring(index + 1);  
        String part2 = numFormat(2, smallOnly);  
        // 把转换好了的整数部分和小数部分重新拼凑一个新的字符串  
        String newS = part1 + part2;  
        return newS;  
    }  
          
    /** 
     * 对传入的数进行四舍五入操作 
     * @param s String 从命令行输入的那个数 
     * @return 四舍五入后的新值 
     */  
    public static String roundString(String loanmoney) {  
        // 如果传入的是空串则继续返回空串  
        if("".equals(loanmoney)) {  
            return "";  
        }  
        // 将这个数转换成 double 类型,并对其进行四舍五入操作  
        double d = Double.parseDouble(loanmoney);  
        // 此操作作用在小数点后两位上  
        d = (d * 100 + 0.5) / 100;  
        // 将 d 进行格式化  
        loanmoney = new java.text.DecimalFormat("##0.000").format(d);  
        // 以小数点为界分割这个字符串  
        int index = loanmoney.indexOf(".");  
        // 这个数的整数部分  
        String intOnly = loanmoney.substring(0, index);  
        // 规定数值的最大长度只能到万亿单位,否则返回 "0"  
        if(intOnly.length() > 13) {  
            System.out.println("输入数据过大!(整数部分最多13位!)");  
            return "";  
        }  
        // 这个数的小数部分  
        String smallOnly = loanmoney.substring(index + 1);  
        // 如果小数部分大于两位,只截取小数点后两位  
        if(smallOnly.length() > 2) {  
            String roundSmall = smallOnly.substring(0, 2);  
            // 把整数部分和新截取的小数部分重新拼凑这个字符串  
            loanmoney = intOnly + "." + roundSmall;  
        }  
        return loanmoney;  
    }  
      
    /** 
     * 把传入的数转换为中文金额大写形式 
     * @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分 
     * @param s String 要转换的字符串 
     * @return 转换好的带单位的中文金额大写形式 
     */  
    private static String numFormat(int flag, String loanmoney) {  
        int sLength = loanmoney.length();  
        // 货币大写形式  
        String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};  
        // 货币单位  
        String unit[] = {"元", "拾", "佰", "仟", "万",   
                // 拾万位到仟万位  
                "拾", "佰", "仟",  
                // 亿位到万亿位  
                "亿", "拾", "佰", "仟", "万"};  
        String small[] = {"分", "角"};  
        // 用来存放转换后的新字符串  
        String newS = "";  
        // 逐位替换为中文大写形式  
        for(int i = 0; i < sLength; i ++) {  
            if(flag == 1) {  
                // 转换整数部分为中文大写形式(带单位)  
                newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1];  
            } else if(flag == 2) {  
                // 转换小数部分(带单位)  
                newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1];  
            }  
        }  
        return newS;  
    }  
      
    /** 
     * 把已经转换好的中文金额大写形式加以改进,清理这个字 
     * 符串里面多余的零,让这个字符串变得更加可观 
     * 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字 
     * 符串应该已经是用中文金额大写形式表示的 
     * @param s String 已经转换好的字符串 
     * @return 改进后的字符串 
     */  
    public static String cleanZero(String loanmoney) {  
        // 如果传入的是空串则继续返回空串  
        if("".equals(loanmoney)) {  
            return "";  
        }  
        // 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯  
        while(loanmoney.charAt(0) == '零') {  
            // 将字符串中的 "零" 和它对应的单位去掉  
        loanmoney = loanmoney.substring(2);  
            // 如果用户当初输入的时候只输入了 0,则只返回一个 "零"  
            if(loanmoney.length() == 0) {  
                return "零";  
            }  
        }  
        // 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位  
        /* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */  
        String regex1[] = {"零仟", "零佰", "零拾"};  
        String regex2[] = {"零亿", "零万", "零元"};  
        String regex3[] = {"亿", "万", "元"};  
        String regex4[] = {"零角", "零分"};  
        // 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零"  
        for(int i = 0; i < 3; i ++) {  
        loanmoney = loanmoney.replaceAll(regex1[i], "零");  
        }  
        // 第二轮转换考虑 "零亿","零万","零元"等情况  
        // "亿","万","元"这些单位有些情况是不能省的,需要保留下来  
        for(int i = 0; i < 3; i ++) {  
            // 当第一轮转换过后有可能有很多个零叠在一起  
            // 要把很多个重复的零变成一个零  
        loanmoney = loanmoney.replaceAll("零零零", "零");  
        loanmoney = loanmoney.replaceAll("零零", "零");  
        loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]);  
        }  
        // 第三轮转换把"零角","零分"字符串省略  
        for(int i = 0; i < 2; i ++) {  
        loanmoney = loanmoney.replaceAll(regex4[i], "");  
        }  
        // 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿"  
        loanmoney = loanmoney.replaceAll("亿万", "亿");  
        return loanmoney;  
    }  
    
    /** 
     * 测试程序的可行性 
     * @param args 
     */  
    public static void main(String[] args) {  
        System.out.println("\n--------将数字转换成中文金额的大写形式------------\n");  
        Trans2RMB t2r = new Trans2RMB();  
        String money= getNum("bbb600ttt98726a");
        System.out.println(money);
        
        String money1= splitNum("17800260026.26");
        System.out.println(money1);
        
        String money2 = roundString("3027830056.34426");
        System.out.println(money2);
        
        String money3 = numFormat(1, "37356653");
        System.out.println(money3);
        
        String money4 = numFormat(2, "34");
        System.out.println(money4);
        
        String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分");
        System.out.println(money5);
        
    } 
}

四、数字格式化(NumberFormat.java)

package com.utils.number;
import java.text.DecimalFormat;
/**
 * 数字格式化
 *
 * @description 
 */
public class NumberFormat {
/** 中文大写数字 */
private static final char[] CN_NUMBERS = {'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};
/** 中文大写金额单位 */
private static final char[] SERIES = {'分','角','元','拾','百','仟','万','拾','百','仟','亿'};
/**
* 四舍五入,由scale参数指 定精度
*
* @param val 原始数据
* @param scale
* @return
*/
public static String round(int val, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
String format = "%." + scale + "f";
return String.format(format, val);
}
/**
* 四舍五入,由scale参数指 定精度 (控制小数点位数)
* @param val 原始数据
* @param scale
* @return
*/
public static String round(double val, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
String format = "%." + scale + "f";
return String.format(format, val);
}
/**
* double数值格式化。该方法会进行四舍五入处理
*
* @param val double数值
* @param format 格式。   “0”表示“ 一个数字”;“#”表示“一个数字,不包括 0” 
* @return
*/
public static String format (double val, String format) {
DecimalFormat myformat = new DecimalFormat();
myformat.applyPattern(format);
return myformat.format(val);
}
/**
* 金额格式化,格式:##,###.00 。该方法会对千分位进行四舍五入处理
*
* @param amount
* @return
*/
public static String financeEN(double amount) {
DecimalFormat myformat = new DecimalFormat();
myformat.applyPattern("##,##0.00");
return myformat.format(amount);
}
/**
* 金额格式化,格式:0.00 。该方法会对千分位进行四舍五入处理
*
* @param amount
* @return
*/
public static String finance(double amount) {
DecimalFormat myformat = new DecimalFormat();
myformat.applyPattern("0.00");
return myformat.format(amount);
}
/**
* 金额单位化输出。格式:####,####.00万,####.0000亿,####.0000万亿
*
* @param amount
* @return
*/
public static String financeShort(double amount) {
String result = null;
if (amount < 10000) {
result = String.format("%.2f", amount);
}else if(10000 <= amount &&  amount< 100000000){
result = Arith.round(amount/10000, 2)+"万";
}else if(100000000 <= amount &&  amount< 1000000000000.00){
result = Arith.round(amount/100000000, 4)+"亿";
}else{
result = Arith.round(amount/1000000000000.00, 4)+"万亿";
}
return result;
}
/**
* 金额格式化。格式:中文大写
* <br>如:100 -> 壹佰元
* 
* @param amount
* @return
*/
public static String financeCN(double amount) {
StringBuffer result = new StringBuffer();
/** 格式金额,这里会保留两位小数,四舍五入 */
DecimalFormat myformat = new DecimalFormat();
myformat.applyPattern("#.00");
String amountStr = myformat.format(amount);
String numStr = amountStr.replace(".", "");
int length = numStr.length();
for (int i=0; i<length; i++) {
int num = Integer.parseInt(String.valueOf(numStr.charAt(i)));
result.append(CN_NUMBERS[num]);
int flag = 0;
for(int j = i+1; j < length;j++){
int numEnd = Integer.parseInt(String.valueOf(numStr.charAt(j)));
if(numEnd == 0){
flag += 1; 
}
}
result.append(SERIES[length-1-i]);
if(flag == length-i-1){
if(flag == 2){
result.append("整");
}else if(flag < 2){
result.append("");
}else if(flag >= 7 && flag < 10){
result.append("万元整");
}else{
result.append("元整");
}
break;
}
}
return result.toString();
}
public static void main(String[] args) {
//四舍五入,由scale参数指 定精度 (控制小数点位数)
System.out.println(round(3.141592657, 5));
//金额格式化,格式:##,###.00 。该方法会对千分位进行四舍五入处理
System.out.println(financeEN(533.893365));
//金额格式化,格式:0.00 。该方法会对千分位进行四舍五入处理
System.out.println(finance(23.983737));
//金额单位化输出。格式:####,####.00万,####.0000亿,####.0000万亿
System.out.println(financeShort(2827627.97262));
//金额格式化。格式:中文大写
System.out.println(financeCN(947400900));
}
}

五、大数高精度计算工具(Arith.java)

package com.utils.number;
import java.math.BigDecimal;
import play.exceptions.TemplateExecutionException.DoBodyException;
/**
 * 算术运算工具类
 *
 * @description 
 *
 * @author lhf
 * @createDate 2018年7月13日
 */
public class Arith {
/**
* 加法运算
*
* @param valA
*            加数
* @param valB
*            加数
* @return
*
*/
public static double add(double valA, double valB) {
BigDecimal a = new BigDecimal(Double.toString(valA));
BigDecimal b = new BigDecimal(Double.toString(valB));
return a.add(b).doubleValue();
}
/**
* 减法运算
*
* @param valA
*            被减数A
* @param valB
*            减数B
* @return 差
*/
public static double sub(double valA, double valB) {
BigDecimal a = new BigDecimal(Double.toString(valA));
BigDecimal b = new BigDecimal(Double.toString(valB));
return a.subtract(b).doubleValue();
}
/**
* 乘法运算
*
* @param valA
*            被乘数A
* @param valB
*            乘数B
* @return 积
*/
public static double mul(double valA, double valB) {
BigDecimal a = new BigDecimal(Double.toString(valA));
BigDecimal b = new BigDecimal(Double.toString(valB));
return a.multiply(b).doubleValue();
}
/**
* 除法运算。当发生除不尽的情况时,数字四舍五入,由scale参数指 定精度。
*
* @param valA
*            被除数
* @param valB
*            除数
* @param scale
*            精度
* @return
*/
public static double div(double valA, double valB, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
BigDecimal a = new BigDecimal(Double.toString(valA));
BigDecimal b = new BigDecimal(Double.toString(valB));
return a.divide(b, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 除法运算。当发生除不尽的情况时,数字向上舍入,由scale参数指 定精度。此舍入模式始终不会减少计算值的大小。
*
* @param valA
*            被除数
* @param valB
*            除数
* @param scale
*            精度
* @return
*/
public static double divUp(double valA, double valB, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
BigDecimal a = new BigDecimal(Double.toString(valA));
BigDecimal b = new BigDecimal(Double.toString(valB));
return a.divide(b, scale, BigDecimal.ROUND_UP).doubleValue();
}
/**
* 除法运算。当发生除不尽的情况时,数字向下舍入,由scale参数指 定精度。此舍入模式始终不会增加计算值的大小。
*
* @param valA
*            被除数
* @param valB
*            除数
* @param scale
*            精度
* @return
*/
public static double divDown(double valA, double valB, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
BigDecimal a = new BigDecimal(Double.toString(valA));
BigDecimal b = new BigDecimal(Double.toString(valB));
return a.divide(b, scale, BigDecimal.ROUND_DOWN).doubleValue();
}
/**
* 四舍五入。由scale参数指 定精度。
*
* @param val
*            原始数字
* @param scale
* @return 四舍五入后的数字
*/
public static double round(double val, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
BigDecimal b = new BigDecimal(Double.toString(val));
return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 多个加数的加法运算
* 
* @param valA
*            被加数
* @param ds
*            多个加数
* @return
*/
public static double add(double valA, double... ds) {
BigDecimal sum = new BigDecimal(Double.toString(valA));
for (int i = 0; i < ds.length; i++) {
sum = sum.add(new BigDecimal(Double.toString(ds[i])));
}
return sum.doubleValue();
}
/**
* 多个减数的减法运算
* 
* @param valA
*            被减数
* @param ds
*            多个减数
* @return
*/
public static double sub(double valA, double... ds) {
BigDecimal result = new BigDecimal(Double.toString(valA));
for (int i = 0; i < ds.length; i++) {
result = result.subtract(new BigDecimal(Double.toString(ds[i])));
}
return result.doubleValue();
}
/**
* 多个乘数的乘法运算
* 
* @param valA
* @param ds
* @return
*/
public static double mul(double valA, double... ds) {
BigDecimal result = new BigDecimal(Double.toString(valA));
for (int i = 0; i < ds.length; i++) {
result = result.multiply(new BigDecimal(Double.toString(ds[i])));
}
return result.doubleValue();
}
/**
* 多个除数的除法运算,中间过程四舍五入取小数点后10位,最终结果四舍五入取指定的小数点后位数
* 
* @param valA
* @param scale
*            最终结果的精度
* @param ds
* @return
*/
public static double div(double valA, int scale, double... ds) {
double result = valA;
for (int i = 0; i < ds.length; i++) {
if (ds[i] == 0) {
throw new IllegalArgumentException("除数不能为0!");
}
result = Arith.div(result, ds[i], 10);
}
return Arith.round(result, scale);
}
/**
* 舍入远离零的舍入模式。在丢弃非零部分之前始终增加数字。注意,此舍入模式始终不会减少计算值的大小。由scale参数指 定精度。
*
* @param val 原始数字
* @param scale
* @return 向上舍入的数字
*/
public static double up(double val, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
BigDecimal b = new BigDecimal(Double.toString(val));
return b.setScale(scale, BigDecimal.ROUND_UP).doubleValue();
}
/**
* 接近零的舍入模式。在丢弃某部分之前始终不增加数字(即截短)。注意,此舍入模式始终不会增加计算值的大小。由scale参数指 定精度。
*
* @param val 原始数字
* @param scale
* @return 向下舍入的数字
*/
public static double down(double val, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("精确度不能小于0!");
}
BigDecimal b = new BigDecimal(Double.toString(val));
return b.setScale(scale, BigDecimal.ROUND_DOWN).doubleValue();
}
public static void main(String[] args) {
double d1 = 1524.090872927;
double d2 = 287627.00098726;
double d3 = 1.000005;
//加法
System.out.println(add(d1,d2));
//减法
System.out.println(sub(d2,d1));
//乘法
System.out.println(mul(d1,d3));
//除法
System.out.println(div(d2,d1,4));
}
}

六、Java拼装生成一个表格

 SignKeyWordType.java

package com.lhf2;
/**
 *  枚举类型:关键字类型
 *
 * @description 
 *
 * @author lhf
 * @createDate 2018年7月13日
 */
public enum SignKeyWordType {
/** 0:默认颜色 */
DEFAULTCOLOR(0,"color:#FFFFFF;"),
/** 1:甲 */
LOANER(1,"sign_loaner"),
/** 2:乙 */
INVESTOR(2,"sign_investor_", "_i"),
/** 3:丙 */
DEBTER(3,"sign_debter"),
/** 4:丁 */
CLAIMER(4,"sign_claimer_", "_d"),
/** 5: 平台*/
PLATFORM(5,"sign_platform")
;
/** 设备类型标识码 */
public int code;
/** 设备名称  */
public String value;
/** 设备名称-结束标志位  */
public String value_suffix;
private SignKeyWordType(int code, String value) {
this.code = code;
this.value = value;
}
private SignKeyWordType(int code, String value, String value_suffix) {
this.code = code;
this.value = value;
this.value_suffix = value_suffix;
}
public static SignKeyWordType getEnum(int code){
SignKeyWordType[] values = SignKeyWordType.values();
for (SignKeyWordType cli : values) {
if (cli.code == code) {
return cli;
}
}
return null;
} 
}

eqbTable.java

package com.lhf2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.utils.pdf.PDFKeyLocation;
public class eqbTable {
public static void main(String[] args) {
List<Map<String, String>> investList = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("type", "1");
investList.add(map1);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("type", "1");
investList.add(map2);
Map<String, String> map3 = new HashMap<String, String>();
map3.put("type", "2");
investList.add(map3);
Map<String, String> map4 = new HashMap<String, String>();
map4.put("type", "1");
investList.add(map4);
Map<String, String> map5 = new HashMap<String, String>();
map5.put("type", "2");
investList.add(map5);
Map<String, String> map6 = new HashMap<String, String>();
map6.put("type", "1");
investList.add(map6);
Map<String, String> map7 = new HashMap<String, String>();
map7.put("type", "1");
investList.add(map7);
Map<String, String> map8 = new HashMap<String, String>();
map8.put("type", "2");
investList.add(map8);
Map<String, String> map9 = new HashMap<String, String>();
map9.put("type", "1");
investList.add(map9);
Map<String, String> map10 = new HashMap<String, String>();
map10.put("type", "2");
investList.add(map10);
Map<String, String> map11 = new HashMap<String, String>();
map11.put("type", "2");
investList.add(map11);
int tds = 4;  //签章列数,固定为4列
StringBuffer sign_buffer = new StringBuffer("");
//表头
sign_buffer.append("<table style='margin-left:30px;margin-top:0px;' border='1px'>");
//第一行:甲方
sign_buffer.append("<tr style='height:100px;'>");
sign_buffer.append("<td>甲方:&nbsp;&nbsp;</td>");
sign_buffer.append("<td colspan='"+tds+"'><span style='"+SignKeyWordType.DEFAULTCOLOR.value+"'>"+SignKeyWordType.LOANER.value+"</span></td>");
sign_buffer.append("</tr>");
Map<Integer, Boolean> trHasCompany = new HashMap<Integer, Boolean>();  //有企业用户的行
for (int i=0; i<investList.size(); i++) {
int trNum = i/tds+1;  //所属行号
if ("2".equals(investList.get(i).get("type"))) {
trHasCompany.put(trNum, true);
}
}
for (int i=0; i<investList.size(); i++) {
int trNum = i/tds+1;  //所属行号
if (i % tds == 0) {  //每行的开始
if (trNum == 1) { //第一行
if (trHasCompany.containsKey(trNum)) {  //包含企业用户
sign_buffer.append("<tr style='height:100px;'><td>乙方:&nbsp;&nbsp;</td>");
} else {
sign_buffer.append("<tr style='height:50px;'><td>乙方:&nbsp;&nbsp;</td>");
}
} else {
if (trHasCompany.containsKey(trNum)) {  //包含企业用户
sign_buffer.append("<tr style='height:100px;'><td>&nbsp;&nbsp;</td>");
} else {
sign_buffer.append("<tr style='height:50px;'><td>&nbsp;&nbsp;</td>");
}
}
}
String id = PDFKeyLocation.formatKeyToIdentified(i+1+"");
sign_buffer.append("<td><span style='"+SignKeyWordType.DEFAULTCOLOR.value+"'>"+SignKeyWordType.INVESTOR.value+id+SignKeyWordType.INVESTOR.value_suffix+"</span></td>");
if ((i+1) % tds == 0) {  //每行的结束
sign_buffer.append("</tr>");
}
}
if(investList.size() % tds != 0){  //最后一行没有结束,需要补齐td
int addTd = tds - (investList.size() % tds);  //需要补充的td数
for(int i = 0; i < addTd; i++){
sign_buffer.append("<td>&nbsp;</td>");
if(i+1 == addTd){
sign_buffer.append("</tr>");
}
}
}
//最后一行:丙方
sign_buffer.append("<tr style='height:100px;'>");
sign_buffer.append("<td>丙方:&nbsp;&nbsp;</td>");
sign_buffer.append("<td colspan='"+tds+"'><span style='"+SignKeyWordType.DEFAULTCOLOR.value+"'>"+SignKeyWordType.LOANER.value+"</span></td>");
sign_buffer.append("</tr>");
//表头
sign_buffer.append("</table>");
System.out.println(sign_buffer.toString());
}
}

好了,今天的分享就到这里,暂时就分享这些工具类,以后有的话,会继续更新,如果对你有帮助,就给我点个赞,表示支持;不喜勿喷!

打开App,阅读手记
6人推荐
发表评论
随时随地看视频慕课网APP