package com.util; import java.text.DecimalFormat; import java.util.Random; /** * StringUtil.java * @author xiongmin */ public class StringUtil { /** * 生成一个定长的纯0字符串 * @param length 字符串长度 * @return 纯0字符串 */ public static String zeroString(int length) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { sb.append('0'); } return sb.toString(); } public static String toFixdLengthString(int num, int fixdlenth) { StringBuffer sb = new StringBuffer(); String strNum = String.valueOf(num); if (fixdlenth - strNum.length() >= 0) { sb.append(StringUtil.zeroString(fixdlenth - strNum.length())); } else { throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth + "的字符串发生异常!"); } sb.append(strNum); return sb.toString(); } public static String getUniqueString(int length){ String str = "abcdefghijklmnopqrstvuwxyz0123456789ABCDEFGHIJKLMNOPQRSTVUWXYZ"; int strLen = str.length(); Random rand = new Random(); StringBuilder sb = new StringBuilder(); for(int i=0;i<length;i++){ int index = rand.nextInt(strLen); sb.append(str.charAt(index)); } return sb.toString(); } /** * 将double数据保留两位小数 * @param value * @param value2 */ public static String getDoubleTwo(String value) { DecimalFormat df = new DecimalFormat("0.00"); double num1 = Double.parseDouble(value); String back = df.format(num1); return back; } /** * 将字符串转换doule保留两位数据转换为百分比 * @param value * @param value2 */ public static String getBaiFenBi(String value) { DecimalFormat df = new DecimalFormat("0.00"); double num1 = Double.parseDouble(value); String num2 = df.format(num1); double num3 = Double.parseDouble(num2) * 100; int num4 = (int)num3; String back = num4 + "%"; return back; } /** * 取两double值的商且保留两位小数 * @param value * @param value2 */ public static String getHundred(String value, String value2) { DecimalFormat df = new DecimalFormat("0.00"); double num1 = Double.parseDouble(value); double num2 = Double.parseDouble(value2); double num3; if (num2 > 0) { num3 = num1 / num2; } else { num3 = 0; } return df.format(num3); } /** * 取两double值的商且保留两位小数,转换为百分比,取绝对值 * @param value * @param value2 * @return */ public static String getHundredBfb(String value, String value2) { String str = getHundred(value,value2); double dou = Double.parseDouble(str) * 100; int num = Math.abs((int)dou); String back = num + "%"; return back; } /** * null值转换 * @return */ public static String strNullZh(String str){ if(null == str || str.equals("")){ return "0"; }else{ return str; } } public static void main(String[] args) { long start = System.currentTimeMillis(); for(int i=0;i<10000;i++){ String s = StringUtil.getUniqueString(20); System.out.println(s); } long end = System.currentTimeMillis(); System.out.println(end-start); } }
String 工具类
猜你喜欢
转载自x125858805.iteye.com/blog/2234163
今日推荐
周排行