簡體   English   中英

Java整數部分填充

[英]Java integer part padding

對不起,我最初想要做它在PHP PHP整數部分填充 ,但意識到我會做它用Java中的代碼,另一部分

所以我需要格式化整數部分至少2個字符的數字

2.11-> 02.11
22.11-> 22.11
222.11-> 222.11
2.1111121-> 02.1111121

double x=2.11; 
System.out.println(String.format("%08.5f", x));

可以做到,但是令人討厭的尾隨零,我想擁有一個任意大的浮動部分

String.format("%02d%s", (int) x, String.valueOf(x-(int) x).substring(1))

完全丑陋且不精確(給出02.1099 ...)

new DecimalFormat("00.#############").format(x)

將截斷浮動部分

尋求更好的解決方案

我能帶的最好的是

public static String pad(String s){
    String[] p = s.split("\\.");
    if (2 == p.length){
        return String.format("%02d.%s", Integer.parseInt(p[0]), p[1]);
    }
    return String.format("%02d", Integer.parseInt(p[0]));
}

pad(String.valueOf(1.11111118))-> 01.11111118

這是使用DecimalFormat的單線:

new DecimalFormat("00." + (x + "").replaceAll(".", "#")).format(x)

它將您的十進制格式設置為00。############# ...,其中“ ############ ...”的長度來自長度小數點后的數字(多余的“#”無效)。

如果願意,可以使用String.valueOf(x)代替(x + "")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM