Java integer part padding

夙愿已清 提交于 2019-12-12 00:52:36

问题


Sorry I was initially wanting to do it in php PHP integer part padding, but realised I will do it in Java in another part of code

So I need to format numbers with the integer part at least 2 chars

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));

could do it, but it's annoying the right trailing zeros, I would like to have an arbitrary large floating part

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

is totally ugly and unexact (gives 02.1099...)

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

will truncate floating part

thx for any better solutions


回答1:


the best I could come with is

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




回答2:


Here's an one-liner using DecimalFormat:

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

It formats your decimal as 00.#############..., where the length of "#############..." comes from the length of your decimal ("#"s in excess does nothing).

You can use String.valueOf(x) in place of (x + "") if you wish.



来源:https://stackoverflow.com/questions/11383859/java-integer-part-padding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!