zoukankan      html  css  js  c++  java
  • 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...

  • 相关阅读:
    Git 思想和工作原理
    scala 内部类
    nginx -stream(tcp连接)反向代理配置 实现代理ldap转发
    【转载】Keepalived安装使用详解
    【转载】Linux内存中buffer和 cached的比较
    【转载】Vmware Vconverter从物理机迁移系统到虚拟机P2V
    InfluxDB 备份和恢复
    Mongodb 主从同步
    Redis主从同步
    ActiveMQ 高可用集群安装、配置(ZooKeeper + LevelDB)
  • 原文地址:https://www.cnblogs.com/cold-ice/p/6380932.html
Copyright © 2011-2022 走看看