Search code examples
javanumbersformatpad

Java integer part padding


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


Solution

  • 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