簡體   English   中英

刪除常量的結尾數字-Java

[英]Remove trailing digits for a constant - Java

我的字段長度不變4 因此,我需要以下格式的輸出:

Input  Output

1   -    0001

10   -   0010

999  -  0999

1111 -  1111

12345 - 1234

我使用String.format("%04d", inputValue);

如何實現最后一個?

如果您只想使用前四位數字,可以使用

String.format("%04d", inputValue).substring(0, 4);

要擺脫前導零,您可以使用

private static String limitToSeven(final int num) {
    String str = String.format("%07d", num).replaceAll("^0+", "");
    return  str.length() <= 7 ? str : str.substring(0,7);
}

暫無
暫無

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

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