0

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?

user442928
  • 1
  • 1
  • 3

3 Answers3

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
  • 1
    To 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];
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.

Community
  • 1
  • 1
ddmps
  • 4,350
  • 1
  • 19
  • 34