2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Convert the numbers into words in readable format using Java

May be my question going to look silly but someone asked me this one to me and still struggling to find out best solution for this.

Requirement : 

           9083 = Nine thousand eighty three
           701 = Seven hundred one

I want that just made a trial and share the code snippet.

userimage

You have a very strong question and so many scenario we came across this kind of scenarios across the development period. Anyway you can now find the snippet and just run on your environment to see the result.


public class NamesArray {
	protected static final String[] specialNames = { "", " thousand", " million", " billion", " trillion",
			" quadrillion", " quintillion" };

	protected static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty", " fifty", " sixty",
			" seventy", " eighty", " ninety" };

	protected static final String[] numNames = { "", " one", " two", " three", " four", " five", " six", " seven",
			" eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen",
			" seventeen", " eighteen", " nineteen" };
}


package com.xyz.conversion;

public class NumbersToWord

{

	private String convertLessThanOneThousand(int number) {
		String current;

		if (number % 100 < 20) {
			current = NamesArray.numNames[number % 100];
			number /= 100;
		} else {
			current = NamesArray.numNames[number % 10];
			number /= 10;

			current = NamesArray.tensNames[number % 10] + current;
			number /= 10;
		}
		if (number == 0)
			return current;
		return NamesArray.numNames[number] + " hundred" + current;
	}

	public String convert(int number) {

		if (number == 0) {
			return "zero";
		}

		String prefix = "";

		if (number < 0) {
			number = -number;
			prefix = "negative";
		}

		String current = "";
		int place = 0;

		do {
			int n = number % 1000;
			if (n != 0) {
				String s = convertLessThanOneThousand(n);
				current = s + NamesArray.specialNames[place] + current;
			}
			place++;
			number /= 1000;
		} while (number > 0);

		return (prefix + current).trim();
	}
	public static void main(String[] args) {
		NumbersToWord numbersToWord = new NumbersToWord();
		System.out.println("Given Number : "+9083);
		System.out.println("In Words : " + numbersToWord.convert(9083));
	}
}

Result :


Given Number : 9083
In Words : nine thousand eighty three
Answer is