Java基础复习之String字符串format处理

  针对String字符串的一个小处理,需求很简单:一个string字符串仅显示length的前4位数字(不包含小数点),若length超过4位后面隐藏显示为“..." 具体结果及代码在下面;使用了常用的2种小方法实现其一是substring字符串截取;其二是正则表达式判断均能满足这个需求。

public static void main(String[] args) {
double d1 = 1234;
double d2 = 123456789;
double d3 = 123.99;
double d4 = 123.9;
double d5 = 12345.99;
double d6 = 1.99;
double d7 = 1234.99;

System.out.println(format(d1));
System.out.println(formats(d2));
System.out.println(formats(d3));
System.out.println(formats(d4));
System.out.println(format(d5));
System.out.println(format(d6));
System.out.println(format(d7));
}

public static String format(double d){
DecimalFormat df = new DecimalFormat("0.##");

String result;
String t = df.format(d);

if (t.indexOf(".") >= 4 && t.length() > 5){
return t.substring(0, 4) + "...";
} else if (t.indexOf(".") > 0 && t.length() > 5){
return t.substring(0, 5) + "...";
} else if (t.indexOf(".") < 0 && t.length() > 4) {
return t.substring(0, 4) + "...";
} else {
return t;
}
}
public static String formats(double d) {
String t = new DecimalFormat("0.##").format(d);
if (t.length() <= 4 || (t.length() == 5 && t.indexOf(".") > 0)){
return t;
}

Pattern p = Pattern.compile("^(\d{4}|(\d{3}\.\d{1}))");
Matcher m = p.matcher(t);
while (m.find()) {
return m.group() + "...";
}

return t;
}

显示结果:依次为:

1234
1234...
123.9...
123.9
1234...
1.99
1234...