你这个需求比较特殊,像1.2 ->01.2,01.2已经不是正常的数字了(正常数字整数部分左侧不能有零),拿只能当字符串来处理了。代码如下:
public class Test {
public static void main(String[] args) {
handle("1.2")
handle("-1.23")
handle("-12.1")
handle("-1.2")
handle("11")
}
private static void handle(String temperature) {
String[] temp = temperature.split("\\.")
if (temp.length == 1) {//无小数点
//整数直接在前面补零
temp[0] = String.format("%03d", Integer.valueOf(temp[0]))
System.out.println(temperature + " ->" + temp[0])
} else if (temp.length == 2) {//有小数点
if (temp[0].startsWith("-")) {//是负数
temp[0] = temp[0].substring(1, temp[0].length())//先去掉负号
if (temp[0].length() + temp[1].length() <3) {//当整数部分长度和小数部分长度相加不足三位时,如1.2,则整数部分补(3-小数部分位数)个零
temp[0] = String.format("%0" + (3 - temp[1].length()) + "d", Integer.valueOf(temp[0]))
}
System.out.println(temperature + " ->" + "-" + temp[0] + "." + temp[1])
} else {//是正数
if (temp[0].length() + temp[1].length() <3) {//当整数部分长度和小数部分长度相加不足三位时,如1.2,则整数部分补(3-小数部分位数)个零
temp[0] = String.format("%0" + (3 - temp[1].length()) + "d", Integer.valueOf(temp[0]))
}
System.out.println(temperature + " ->" + temp[0] + "." + temp[1])
}
}
}
}
运行结果:
int x=(int)(Math.random()*1000)String s = x + ""
List<String> list = new ArrayList<String>()
if(s.length() < 4) {
for(int i = 0i < 4 - s.length()i++) {
list.add("0")
}
}
String result = list.toString().replace("[", "").replace("]", "") + s