Fixed decimal numbers with JAVA

吃可爱长大的小学妹 提交于 2019-12-01 03:03:23

问题


How do I represent numbers in the format

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

The number of digits is always 3.


回答1:


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



回答2:


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.




回答3:


You can use something like this

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



回答4:


Am I missing something obvious here?

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


来源:https://stackoverflow.com/questions/4377209/fixed-decimal-numbers-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!