I would like to format a 3-digit integer
to a 4-digit string
value. Example:
int a = 800;
String b = "0800";
Of course the formatting will be done at String b
statement. Thanks guys!
I would like to format a 3-digit integer
to a 4-digit string
value. Example:
int a = 800;
String b = "0800";
Of course the formatting will be done at String b
statement. Thanks guys!
If you want to have it only once use String.format("%04d", number)
- if you need it more often and want to centralize the pattern (e.g. config file) see the solution below.
Btw. there is an Oracle tutorial on number formatting.
To make it short:
import java.text.*;
public class Demo {
static public void main(String[] args) {
int value = 123;
String pattern="0000";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(output); // 0123
}
}
Hope that helps. *Jost
Please try
String.format("%04d", b);
String b = "0" + a;
Could it be easier?
You can always use Jodd Printf for that. In your case:
Printf.str("%04d", 800);
would do the job. This class was created before Sun added String.format
and has somewhat more formatting options.