详解Java中使用正则表达式来去掉字符串中的0

猿友 2021-08-05 15:08:44 浏览数 (3138)
反馈

当获取了一组数字的字符串,一大串数字前后都有很多个零,但是我们只需要其中准确的数值,那么该如何获取这个准确数值的字符串?下面,将为大家介绍Java中用正则表达式来去掉数字字符串中的多余的零。

我就废话不多说了,大家还是看代码吧

String s="0000000002121210"
s=s.replaceAll("^(0+)", "");
System.out.println(s);

补充:Java中数字处理去掉末尾的0

实例如下所示:

public static String insertComma(String s, int len) {
    if (s == null || s.length() < 1) {
        return "";
    }
    NumberFormat formater = null;
    double num = Double.parseDouble(s);
    if (len == 0) {
        formater = new DecimalFormat("###,###");
 
    } else {
        StringBuffer buff = new StringBuffer();
        buff.append("###,###.");
        for (int i = 0; i < len; i++) {
            buff.append("#");
        }
        formater = new DecimalFormat(buff.toString());
    }
    return formater.format(num);
}
double num = 5.5500; 
DecimalFormat decimalFormat = new DecimalFormat("##########.##########"); 
String numConverted = decimalFormat.format(num); //5.55

利用“########.##########”

以上就是关于Java中如何使用正则表达式来去除一组数字字符串中多余的零的详细内容,希望能给大家一个参考,也希望大家多多支持W3Cschool。如有错误或未考虑完全的地方,望不吝赐教。


0 人点赞