Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Displaying integer values less than 10 with a padded 0  RSS feed

 
D diller
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have an integer value less than 10 (ie one digit), and I want it to still display as 2 digits (just with a leading 0) is there any way to do this while keeping it as an integer (I need to manipulate the variable later easily), or will I have to convert it to a String?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using Jave 1.5 or later, use System.out.printf();
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16026
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by D diller:
... while keeping it as an integer (I need to manipulate the variable later easily), or will I have to convert it to a String?

It sounds like you are confused about data types and what they mean exactly.

An integer is just a number - nothing more, nothing less. It does not have a "format". So, an integer does not have leading zeroes. Whenever you display an integer on screen, you are converting it to text - ASCII characters, or characters in a different encoding, that the computer knows how to display.

Also, variables in Java have a fixed type. A variable's type cannot be changed from int to String.

Normally, if you print an integer with for example System.out.println() without thinking how you want it formatted, the computer will format it as a sequence of decimal digits and those are printed to the screen.

In some cases, like yours, you want the number to be printed with a specific format. So then you need to use classes and methods that allow you to specify the format. You can use System.out.printf(), which is the shortest way to do this, or you could use class java.text.DecimalFormat.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!