Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't String.format() give me a left zero-padded floating point output?

I'm trying to get the decimal 8.6 to render to a left zero-padded string i.e. 08.6.

Why doesn't the following seem to work?

double number = 8.6;
String.format("%03.1f", number); //expect "08.6", get "8.6"

The formatting string seems to be correct. What am I doing wrong?

like image 785
Vishal Kotcherlakota Avatar asked Oct 17 '25 17:10

Vishal Kotcherlakota


1 Answers

It is giving you a left zero-padded floating point output, it's just that the field width of 3 includes the decimal point and the fractional portion (and the sign, if it's negative), so you need to use %04.1f instead for that particular value.

The output of:

public class Test {
    public static void main(String[] args) {
        double number = 8.6;
        System.out.println(String.format("%04.1f", number));
    }
}

is:

08.6
like image 91
paxdiablo Avatar answered Oct 20 '25 07:10

paxdiablo