Number to Words Convert

 

number to Words Convert

public class NumberToWord {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a number (0 to 999): ");

    int num = sc.nextInt();

    System.out.println("Number in words: " + convertToWord(num));

}

public static String convertToWord(int num) {

String[] units = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",

"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };

String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

    if (num < 20) {

    return units[num];

}

if (num < 100) {

return tens[num / 10] + ((num % 10 != 0) ? " " : "") + units[num % 10];

}

return units[num / 100] + " Hundred" + ((num % 100 != 0) ? " " : "") + convertToWord(num % 100)+ "**";

}

}


------------------------------------------------

if (num < 20) {

return units[num];

}

here, if num less than 20 e.g num = 5, then units[5] 

print 5 index is "five".

-------------------------------------------------

if (num < 100) {

return tens[num / 10] + ((num % 10 != 0) ? " " : "") + units[num % 10];

}

here, if num less than 100 e.g. 20 . then tens[num / 10] = 2;

tens[2] index is twenty print. if num % 10 ==0 then print only no space : "" and num % !=0 then print "space"


here, if num is 21 then tens[num/10] = 2, then tens[2] index is "Twenty" , num % 10 != 0 is true print space.

and + units[num % 10] = 1 then units[1] index is "one".


----------------------------------------------------

return units[num / 100] + " Hundred" + ((num % 100 != 0) ? " " : "") + convertToWord(num % 100);

    



here, if num = 102, then units[num / 100] = 1 , units[1] index is one , then add + "hundred"+"

(num % 100 != 0) is true print space. 


convertToWord(num % 100) here use recursion, thats return goes to method and 

num % 100 => 102 % 2 =2;

convertToWord(num % 100) = convertToWord(2

and these goes to given block

if (num < 20) {

    return units[num];

}

unit[2] index is "Two".

Output is : One Hundred Two



Comments