I have to convert int 1 to string 'one', 2 to 'two' etc in java, could any one please explain me how to do that in Java. Is it possible?
Asked
Active
Viewed 7,192 times
0
-
Make a method containg swtich and return the desired string accordingly. – Smit Jun 04 '13 at 17:04
-
No, it is not possible (sarcasm). – Rosdi Kasim Jun 04 '13 at 17:05
-
There is already similar question - http://stackoverflow.com/questions/3299619/algorithm-that-converts-numeric-amount-into-english-words – Ondrej Svejdar Jun 04 '13 at 17:08
3 Answers
1
Yes. Starting with zero, the bottom twenty-one numbers have individual names, then there are patterns up to hundred, thousand, million, and so on.

CPerkins
- 8,968
- 3
- 34
- 47
-
1To add onto this, special case 0. From there, include a negative if necessary. Split the digits into groups of three and use special cases to build those. Then use log10s to figure out what radix the digit is at, apply the proper end (thousand, million, billion). For example: 127233. -> One hundred twenty-seven thousand, two hundred thirty-three. – Jun 04 '13 at 17:10
-
@Legend good point. Edited. I'd +1 your comment, but for some reason, I haven't been able to do that lately from this browser... or acknowledge that I've viewed comments. – CPerkins Jun 04 '13 at 18:13
1
String[] strArr = {"zero","one","two"};
String one = strArr [1];

Sam I am says Reinstate Monica
- 30,851
- 12
- 72
- 100
0
Sure, but there's no magical way of getting it working so you have to code it all manually.
One way is to simply write an switch/case clause returning the converted value, as such:
public static String convertNumber(int i) {
switch(i) {
case 1:
return "one";
case 2:
return "two";
} //etc
}
Another is to add them all to a map and use that, as such:
Map<Integer, String> numbersMap = new TreeMap<Integer,String>();
numbersMap.add(1, "one");
numbersMap.add(2, "two"); //etc
and then use the following to get the desired String:
numbersMap.get(int);
Also, see this for a general solution to "all" numbers.
-
1
-
-
I can use Switch or Map, but I was trying for any generic method which converts numeric number to word format because I might have to display number in hundred's. Thank you. – user442928 Jun 04 '13 at 17:39
-