• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Displaying integer values less than 10 with a padded 0

 
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?
 
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();
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • 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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!