Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top