当获取了一组数字的字符串,一大串数字前后都有很多个零,但是我们只需要其中准确的数值,那么该如何获取这个准确数值的字符串?下面,将为大家介绍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。如有错误或未考虑完全的地方,望不吝赐教。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。