Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java add leading zeros to a number

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));
    }
like image 471
user69514 Avatar asked Mar 31 '10 19:03

user69514


People also ask

How do you add zeros to two digit numbers in Java?

format("%03d", num); 0 - to pad with zeros.

How do you add a leading zero to a string?

You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.

How do you add a leading zero when a number is less than 10?

The safest way is probably to only add zeroes when the length of the column is 1 character: UPDATE Table SET MyCol = '0' + MyCol WHERE LEN(MyCol) = 1; This will cover all numbers under 10 and also ignore any that already have a leading 0.


1 Answers

There's an arguably more elegant solution:

String.format("%03d-%03d-%04d", areaCode, exchangeCode, number)
like image 79
Tomislav Nakic-Alfirevic Avatar answered Sep 23 '22 08:09

Tomislav Nakic-Alfirevic