Java add leading zeros to a number

user69514 picture user69514 · Mar 31, 2010 · Viewed 32.4k times · Source

I need to return a string in the form xxx-xxxx where xxx is a number and xxxx is another number, however when i have leading zeros they disappear. I'm trying number formatter, but it's not working.

 public String toString(){
        NumberFormat nf3 = new DecimalFormat("#000");
        NumberFormat nf4 = new DecimalFormat("#0000");
        if( areaCode != 0)
            return nf3.format(areaCode) + "-" + nf3.format(exchangeCode) + "-" + nf4.format(number);
        else
            return exchangeCode + "-" + number;
    }

}

I figured it out:

 public String toString(){
        NumberFormat nf3 = new DecimalFormat("000");
        NumberFormat nf4 = new DecimalFormat("0000");
        if( areaCode != 0)
            //myFormat.format(new Integer(someValue));
            return nf3.format(new Integer(areaCode)) + "-" + nf3.format(new Integer(exchangeCode)) + "-" + nf4.format(new Integer(number));
        else
            return nf3.format(new Integer(exchangeCode)) + "-" + nf4.format(new Integer(number));
    }

Answer

Tomislav Nakic-Alfirevic picture Tomislav Nakic-Alfirevic · Mar 31, 2010

There's an arguably more elegant solution:

String.format("%03d-%03d-%04d", areaCode, exchangeCode, number)