本文目錄一覽:
- 1、java數字自動補零
- 2、java 右補零問題
- 3、JAVA溫度補0問題?
java數字自動補零
你在數字前面拼三個000,然後取後面三位就好了。
public class Test {
public static void main(String[] args) {
int i = 6;
int j = 10;
System.out.println(“i==” + codeFormat(i));
System.out.println(“i==” + codeFormat(j));
}
public static String codeFormat(int i) {
String str = “000” + String.valueOf(i);
return str.substring(str.length()-3);
}
}
java 右補零問題
用java.text包中的DecimalFormat方法
例子如下:
import java.text.*;
class Main
{
public static void main(String[] args)
{
double d=1.23;
DecimalFormat g=new DecimalFormat(“0.000000”);
System.out.println(g.format(d));
}
}
運行結果 1.230000
JAVA溫度補0問題?
你這個需求比較特殊,像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]);
}
}
}
}
運行結果:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/239747.html