Java Online Compiler
Example: Convert Digit Number to Words in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Convert Digit Number to Words import java.util.Scanner; // Main class containing the entry point of the program public class Main { private static final String[] units = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; private static final String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; private static final String[] scales = { "", "Thousand", "Million", "Billion", "Trillion" }; public static String convertToWords(long number) { if (number == 0) { return "Zero"; } String words = ""; int scaleIndex = 0; while (number > 0) { if (number % 1000 != 0) { words = convertLessThanOneThousand((int) (number % 1000)) + " " + scales[scaleIndex] + " " + words; } number /= 1000; scaleIndex++; } return words.trim(); } private static String convertLessThanOneThousand(int number) { String current; if (number % 100 < 20) { current = units[number % 100]; number /= 100; } else { current = units[number % 10]; number /= 10; current = tens[number % 10] + " " + current; number /= 10; } if (number > 0) { current = units[number] + " Hundred " + current; } return current.trim(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); long number = scanner.nextLong(); scanner.close(); System.out.println("Word representation: " + convertToWords(number)); } }
Output
Clear
ADVERTISEMENTS