Save an integer in two digit format in a variable in Java

后端 未结 4 778
闹比i
闹比i 2020-12-05 18:22

How can I store an integer in two digit format in Java? Like can I set

int a=01;

and print it as 01? Also, not only printing,

相关标签:
4条回答
  • 2020-12-05 18:51

    I think this is what you're looking for:

    int a = 1;
    DecimalFormat formatter = new DecimalFormat("00");
    String aFormatted = formatter.format(a);
    
    System.out.println(aFormatted);
    

    Or, more briefly:

    int a = 1;
    System.out.println(new DecimalFormat("00").format(a));
    

    An int just stores a quantity, and 01 and 1 represent the same quantity so they're stored the same way.

    DecimalFormat builds a String that represents the quantity in a particular format.

    0 讨论(0)
  • 2020-12-05 19:00

    This is not possible, because an integer is an integer. But you can format the Integer, if you want (DecimalFormat).

    0 讨论(0)
  • 2020-12-05 19:03
    // below, %02d says to java that I want my integer to be formatted as a 2 digit representation
    String temp = String.format("%02d", yourIntValue);
    // and if you want to do the reverse
    int i = Integer.parse(temp);
    
    // 2 -> 02 (for example)
    
    0 讨论(0)
  • 2020-12-05 19:10

    look at the below format its work above format can work for me

    System.out.printf("%02d", myNumber)

    0 讨论(0)
提交回复
热议问题