How can I display 1 as 01 in Java when using the g.drawstring command I have tried to look but I don't know what term I should use.
            Asked
            
        
        
            Active
            
        
            Viewed 1,957 times
        
    0
            
            
        - 
                    1What kind of displaying? Printing in output, drawing on screen? – Steyrix Jul 28 '20 at 10:32
 - 
                    2`int i = 1; g.drawString(String.format("%02d", i), x, y)` – Jul 28 '20 at 10:36
 - 
                    1Does this answer your question? [Right padding with zeros in Java](https://stackoverflow.com/questions/12962515/right-padding-with-zeros-in-java) – C. Weber Jul 28 '20 at 10:37
 - 
                    @jibbsie1802 eventhough saka1029 provided answer first in the comments, you can accept one of the answers so everyone will see that the question is closed – Steyrix Jul 28 '20 at 11:27
 
3 Answers
2
            
            
        You can format String and display it like this:
g.drawString(String.format("%02d", 1));
%02d is used for formatting, where 02 states for two digits with leading zero as necessary, and d - decimal number
Source: Official Oracle Documentation on formatting numeric strings
        Steyrix
        
- 2,796
 - 1
 - 9
 - 23
 
0
            
            
        If you want to print a string that contains that number, you can use String.format.
If you write something like String.format("%02d", yourNumber), for yourNumber=1 you will obtain the string 01, so you can use the previous code in a System.out or draw it on screen.
If you want to use g.drawstring, you can use the following code:
g.drawString(String.format("%02d", yourNumber), x, y)
        Calaf
        
- 1,133
 - 2
 - 9
 - 22
 
0
            
            
        You could use Java's String.format() method, like this (recommended)
String.format("%02d", num)
Or if you could write something like this:
String text = (num < 10 ? "0" : "") + num;
        HappyRave
        
- 175
 - 1
 - 4
 - 11