开发者

Convert 1 to 01

I have an int between 1 - 99. How do I 开发者_如何学Cget it to always be a double digit, ie: 01, 04, 21?


Presumably you mean to store the number in a String.

Since JDK1.5 there has been the String.format() method, which will let you do exactly what you want:

String s = String.format("%02d", someNumber);

One of the nice things about String.format() is that you can use it to build up more complex strings without resorting to lots of concatenation, resulting in much cleaner code.

String logMessage = String.format("Error processing record %d of %d: %s", recordNumber, maxRecords, error);


Yet another way

String text = (num < 10 ? "0" : "") + num;

EDIT: The code is short enough that the JIT can compile it to nothing. ;)

long start = System.nanoTime();
for(int i=0;i<100000;i++) {
    for(int num=1;num<100;num++) {
        String text = (num < 10 ? "0" : "") + num;
    }
}
long time = System.nanoTime() - start;
System.out.println(time/99/100000);

prints

0


Using

String.format("%02d", num)

Is probably the best option.


You can do this with NumberFormat:

NumberFormat format = new NumberFormat();
format.setMinimumIntegerDigits(2);
System.out.println(format.format(1));

Note - String.format() is a Java 5 method.

If you're using Java 5 or above you can do:

String.format("%02d", 1);

as mentioned in other answers.


Try this

String.format("%02d", num)


One possible solution:

String.valueOf(number + 100).substring(1);


You can do this by

String.format("%02d", 1)


You can't do it just using an int. You'll have to convert between Strings (for display) and back to ints (for calculations). You can use the Java Formatter to format your Strings based on the input.


I think, I should add the link to the official Java documentation on formatting numeric outputs.

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Sample Snipplet: Prints 00 up to 100

class Main {
    public static void main(String[] args) {
      for(int i=0;i<=100;i++){
        System.out.println(String.format("%02d", i)); 
      }
    }
}

Output:

00
01
...
10
...
100


use number format http://download.oracle.com/javase/6/docs/api/java/text/NumberFormat.html


Or you could just use printf instead of String.format

 for (int i = 0; i <= 100; i++) {
         System.out.printf("%02d%n",i);
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜