开发者

Fixed decimal numbers with JAVA

开发者 https://www.devze.com 2023-01-29 01:55 出处:网络
Howdo Irepresent numbers in theformat 001 = 1 002 = 2 003 = 3 010 = 10 020 = 20 The numberof 开发者_Go百科 digitsisalways3.If you want to output integers such that they always have leading zeros, u

How do I represent numbers in the format

001 = 1
002 = 2
003 = 3
010 = 10
020 = 20

The number of 开发者_Go百科 digits is always 3.


If you want to output integers such that they always have leading zeros, use String.format with a zero before the number of digits in the format string, for example:

int i = 3;
String s = String.format("%03d", i);
System.out.println(s);

Gives the output:

003


Integer.valueOf("020") is sufficient for your purpose. It will give you 20 as a result. After that you can use it as Integer, int or String.


You can use something like this

DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumIntegerDigits(3);
System.err.println(decimalFormat.format(2));


Am I missing something obvious here?

String  num_str = "001"
Integer val     = Integer.parseInt(num_str);
String  answer  = val.toString();
0

精彩评论

暂无评论...
验证码 换一张
取 消