Java add leading zeros to a number....

Posted by user69514 on Stack Overflow See other posts from Stack Overflow or by user69514
Published on 2010-03-31T19:33:42Z Indexed on 2010/03/31 19:53 UTC
Read the original article Hit count: 392

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

© Stack Overflow or respective owner

Related posts about java

Related posts about string-manipulation