This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with int Conversion to String

 
Abiodun Adisa
Ranch Hand
Posts: 495
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 101
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 82
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 495
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks folks i was able to do it using

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Adam Schaible
Ranch Hand
Posts: 101
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper's solution is the one I was looking for - it's definately the best way to do it.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic