| Author |
Help with int Conversion to String
|
Abiodun Adisa
Ranch Hand
Joined: Jan 17, 2002
Posts: 495
|
|
I have an int that i would want to convert to String if the integer is less than 4 digit it should append zeros to fill in the missing digits for example int input=9 the function convertToString(input) should return 0009 int input=19 the function convertToString(input) should return 0019 int input=119 the function convertToString(input) should return 0119 int input=1119 the function convertToString(input) should return 1119
|
 |
Adam Schaible
Ranch Hand
Joined: Oct 04, 2007
Posts: 101
|
|
Where are you getting stuck? This may not be the most efficient psuedo-code, but here's an approach [code] change int to String add "000" in front of string get a substring of string.length-4 - string.length [code] In the two minutes of thinking about it, this is the simplest approach I could come up with. There are several other ways - looping, and conditionals come to mind, but I think we'd all like to avoid control structures when possible.
|
 |
David Irwin
Ranch Hand
Joined: Mar 25, 2004
Posts: 82
|
|
You might try something like the following: It's certainly not optimal given the string concatenation and there's probably some parameter checking you'd want to add but I believe it does what you're looking for. Dave
|
 |
Abiodun Adisa
Ranch Hand
Joined: Jan 17, 2002
Posts: 495
|
|
Thanks folks i was able to do it using
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12909
|
|
Another solution: And one more, for if you're using a Java version older than 5.0: [ November 14, 2007: Message edited by: Jesper Young ]
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Adam Schaible
Ranch Hand
Joined: Oct 04, 2007
Posts: 101
|
|
|
Jesper's solution is the one I was looking for - it's definately the best way to do it.
|
 |
 |
|
|
subject: Help with int Conversion to String
|
|
|