+ 1
How to convert numbers to words(million) in java?
In less than 100 lines, How can I convert numbers to words using java? I can only see tutorials and answers up to 99,999 and I want it up to 999,999,99. Can anyone help me?
3 Answers
0
I'm not sure I correctly understand the problem : do you want to convert an integer to a string, using the comma separator for the thousands ?
If so, formatting works, whatever the number of digits (well as long as it doesn't exceed int range), for example :
int num = 1000000000;
String num_string = String.format("%,d",num);
System.out.println(num_string);
will print 1,000,000,000.
If you're looking for another type of simple formatting, you can look up this site, it's a good summary of available options :
https://www.novixys.com/blog/java-string-format-examples/
If I didn't understand your problem, could you give a more precise example ?
dhm
0
I mean how can I convert a larger digit(million). I can only see on yotube and stack overflow, converting up to 99,999. For example
this is the output
enter a positive integer: 9,000, 000
nine million
0
Ok I get it now, and I've looked at the code you put on the playground.
To expand it for numbers > 99999, I would replace this part :
else if(number<20000)
{
return units[number/1000] + " Thousand " + ((number%1000>0)? convert(number%1000):"");
}
return tens[number/10000] + ((number%10000>0)? convert(number%10000):"Thousand" );
with this :
else if(number<1000000)
{
return convert(number/1000) + " Thousand" + ((number%1000>0)? " " + convert(number%1000):"");
}
return convert(number/1000000) + " Million" + ((number%1000000>0)? " " + convert(number%1000000):"");
In my opinion : you don't need to bother with lines to manage the thousands (in your code, the <20k and <99999 are dealt with separately) : since you have defined the beahavior for 0 to hundred, rely on the recursion of your convert function to deal with the different cases. Hence the first else if.
Then deal with the >=1million case : just use the same call to the convert function for the million part and rely on recursion again. Then call it for the number%1000000 part if it isn't 0.
Tell me if something's not clear in the explanation or if once again I haven't understood your problem.
Edit : Based on your code, I've put the version implementing my modifications in public view under the name java_int_in_words, if it helps clarify what I'm saying