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));
}
format("%03d", num); 0 - to pad with zeros.
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.
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.
There's an arguably more elegant solution:
String.format("%03d-%03d-%04d", areaCode, exchangeCode, number)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With