Last active
March 14, 2021 21:49
-
-
Save Ismail-Ai404/5f3f3cf392776f4cb31ae3b6117fbc9c to your computer and use it in GitHub Desktop.
Numbers to words by method.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NumberstoWords { | |
public static void main(String[] args) { | |
System.out.println(amountInWords(100)); | |
} | |
public static String amountInWords(int amount) { | |
int t=0; | |
int h=0; | |
if(amount>=10000) return "Invalid Input (Must be less than 10000)"; | |
if (amount==0) return "Zero"; | |
String[] s1 = {"","One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ", | |
"Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", | |
"Seventeen ", "Eighteen ", "Nineteen "}; | |
String[] s2 = | |
{ "", | |
"Ten ", | |
"Twenty ", | |
"Thirty ", | |
"Forty ", | |
"Fifty ", | |
"Sixty ", | |
"Seventy ", | |
"Eighty ", | |
"Ninety " | |
}; | |
String[] s3 = {"","Thousand ", "Hundred "}; | |
int[] a=new int[5]; | |
int c=0; | |
while (amount > 0) | |
{ | |
a[c]=(amount%10); | |
c++; | |
amount /= 10; | |
} | |
int[] b=new int[5]; | |
int j=b.length-1; | |
for (int i = 0; i <b.length ; i++,j--) | |
{ | |
b[i]=a[j]; | |
} | |
int sum=0; | |
if (b[1]!=0) t=1; | |
if (b[2]!=0) h=2; | |
if (b[3]*10+b[4]<20) | |
{ sum=b[3]*10+b[4]; | |
String toWords1= s1[b[1]]+s3[t]+s1[b[2]]+s3[h]+s1[sum]; | |
return toWords1; | |
} | |
else { | |
String toWords0 = s1[b[1]] + s3[t] + s1[b[2]] + s3[h] + s2[b[3]] + s1[b[4]]; | |
return toWords0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment