Integer to String program

Dear all,

If I would like to change to an integer 2 to a string 02,  how to implement in java program?

In C,  just
         i = 2;
         printf("%02d", i);

How about in java?

Benson
benson031397Asked:
Who is Participating?
 
_lychee_Connect With a Mentor Commented:
should i answer then?
0
 
_lychee_Commented:
i think:

int i = 2;
System.out.println(new java.text.DecimalFormat("00").format(i));

not very sure cos i don't have java installed at the mmt...
0
 
JodCommented:
There are two soltutions.

To do it yourself you would need to make a method like this...

public String makeStringWithLeadingZero(int i) {
  String s = i.toString();
  if (s.length() == 1) s = "0" + s;
  return s;
}

int i = 1;
System.out.println("int i " + i + "turned into String " + makeStringWithLeadingZero(i));


This will turn

55 into String "10" and 1 into String "01"


Or download this...

http://www.efd.lth.se/~d93hb/java/printf/
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
JodCommented:
SOrry lychee - didn't see your comment while writing my answer...
0
 
_lychee_Commented:
it's alright :>
0
 
_lychee_Commented:
eh...

i think u should change
i.toString()
to
Integer.toString(i)

or does i.toString() really work?
0
 
JodCommented:
And my answer is not even right! It should be...

public String makeStringWithLeadingZero(int i) {
  String s = Integer.toString(i);
  if (s.length() == 1) s = "0" + s;
  return s;
}


To be honest,

System.out.println(new java.text.DecimalFormat("00").format(i));

is a neater solution if it works for you benson.

0
 
JodCommented:
Missed your comment again!

No, i.toString() will never work in a zillion years.

Just wasn't thinking when I wrote the answer...




0
 
benson031397Author Commented:
lychee has given the answer.

Thanks lychee
0
 
JodCommented:
Even I prefer lychee's answer...
0
All Courses

From novice to tech pro — start learning today.