How to Convert Number to Words in Java

How to convert number to words in java

Here is the code, I don't think there is any method in SE.

It basically converts number to string and parses String and associates it with the weight

for example

1000

1 is treated as thousand position and 1 gets mapped to "one" and thousand because of position



This is the code from the website:

English

import java.text.DecimalFormat;

public class EnglishNumberToWords {

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

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

private EnglishNumberToWords() {}

private static String convertLessThanOneThousand(int number) {
String soFar;

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

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


public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }

String snumber = Long.toString(number);

// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);

// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9,12));

String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1 :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
break;
default :
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
}
String result = tradBillions;

String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
}
result = result + tradMillions;

String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1 :
tradHundredThousands = "one thousand ";
break;
default :
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
}
result = result + tradHundredThousands;

String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;

// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}

/**
* testing
* @param args
*/
public static void main(String[] args) {
System.out.println("*** " + EnglishNumberToWords.convert(0));
System.out.println("*** " + EnglishNumberToWords.convert(1));
System.out.println("*** " + EnglishNumberToWords.convert(16));
System.out.println("*** " + EnglishNumberToWords.convert(100));
System.out.println("*** " + EnglishNumberToWords.convert(118));
System.out.println("*** " + EnglishNumberToWords.convert(200));
System.out.println("*** " + EnglishNumberToWords.convert(219));
System.out.println("*** " + EnglishNumberToWords.convert(800));
System.out.println("*** " + EnglishNumberToWords.convert(801));
System.out.println("*** " + EnglishNumberToWords.convert(1316));
System.out.println("*** " + EnglishNumberToWords.convert(1000000));
System.out.println("*** " + EnglishNumberToWords.convert(2000000));
System.out.println("*** " + EnglishNumberToWords.convert(3000200));
System.out.println("*** " + EnglishNumberToWords.convert(700000));
System.out.println("*** " + EnglishNumberToWords.convert(9000000));
System.out.println("*** " + EnglishNumberToWords.convert(9001000));
System.out.println("*** " + EnglishNumberToWords.convert(123456789));
System.out.println("*** " + EnglishNumberToWords.convert(2147483647));
System.out.println("*** " + EnglishNumberToWords.convert(3000000010L));

/*
*** zero
*** one
*** sixteen
*** one hundred
*** one hundred eighteen
*** two hundred
*** two hundred nineteen
*** eight hundred
*** eight hundred one
*** one thousand three hundred sixteen
*** one million
*** two millions
*** three millions two hundred
*** seven hundred thousand
*** nine millions
*** nine millions one thousand
*** one hundred twenty three millions four hundred
** fifty six thousand seven hundred eighty nine
*** two billion one hundred forty seven millions
** four hundred eighty three thousand six hundred forty seven
*** three billion ten
**/
}
}

Français
Quite different than the english version but french is a lot more difficult!

package com.rgagnon.howto;

import java.text.*;

class FrenchNumberToWords {
private static final String[] dizaineNames = {
"",
"",
"vingt",
"trente",
"quarante",
"cinquante",
"soixante",
"soixante",
"quatre-vingt",
"quatre-vingt"
};

private static final String[] uniteNames1 = {
"",
"un",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix",
"onze",
"douze",
"treize",
"quatorze",
"quinze",
"seize",
"dix-sept",
"dix-huit",
"dix-neuf"
};

private static final String[] uniteNames2 = {
"",
"",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix"
};

private FrenchNumberToWords() {}

private static String convertZeroToHundred(int number) {

int laDizaine = number / 10;
int lUnite = number % 10;
String resultat = "";

switch (laDizaine) {
case 1 :
case 7 :
case 9 :
lUnite = lUnite + 10;
break;
default:
}

// séparateur "-" "et" ""
String laLiaison = "";
if (laDizaine > 1) {
laLiaison = "-";
}
// cas particuliers
switch (lUnite) {
case 0:
laLiaison = "";
break;
case 1 :
if (laDizaine == 8) {
laLiaison = "-";
}
else {
laLiaison = " et ";
}
break;
case 11 :
if (laDizaine==7) {
laLiaison = " et ";
}
break;
default:
}

// dizaines en lettres
switch (laDizaine) {
case 0:
resultat = uniteNames1[lUnite];
break;
case 8 :
if (lUnite == 0) {
resultat = dizaineNames[laDizaine];
}
else {
resultat = dizaineNames[laDizaine]
+ laLiaison + uniteNames1[lUnite];
}
break;
default :
resultat = dizaineNames[laDizaine]
+ laLiaison + uniteNames1[lUnite];
}
return resultat;
}

private static String convertLessThanOneThousand(int number) {

int lesCentaines = number / 100;
int leReste = number % 100;
String sReste = convertZeroToHundred(leReste);

String resultat;
switch (lesCentaines) {
case 0:
resultat = sReste;
break;
case 1 :
if (leReste > 0) {
resultat = "cent " + sReste;
}
else {
resultat = "cent";
}
break;
default :
if (leReste > 0) {
resultat = uniteNames2[lesCentaines] + " cent " + sReste;
}
else {
resultat = uniteNames2[lesCentaines] + " cents";
}
}
return resultat;
}

public static String convert(long number) {
// 0 à 999 999 999 999
if (number == 0) { return "zéro"; }

String snumber = Long.toString(number);

// pad des "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);

// XXXnnnnnnnnn
int lesMilliards = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int lesMillions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int lesCentMille = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int lesMille = Integer.parseInt(snumber.substring(9,12));

String tradMilliards;
switch (lesMilliards) {
case 0:
tradMilliards = "";
break;
case 1 :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliard ";
break;
default :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliards ";
}
String resultat = tradMilliards;

String tradMillions;
switch (lesMillions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " millions ";
}
resultat = resultat + tradMillions;

String tradCentMille;
switch (lesCentMille) {
case 0:
tradCentMille = "";
break;
case 1 :
tradCentMille = "mille ";
break;
default :
tradCentMille = convertLessThanOneThousand(lesCentMille)
+ " mille ";
}
resultat = resultat + tradCentMille;

String tradMille;
tradMille = convertLessThanOneThousand(lesMille);
resultat = resultat + tradMille;

return resultat;
}

public static void main(String[] args) {
System.out.println("*** " + FrenchNumberToWords.convert(0));
System.out.println("*** " + FrenchNumberToWords.convert(9));
System.out.println("*** " + FrenchNumberToWords.convert(19));
System.out.println("*** " + FrenchNumberToWords.convert(21));
System.out.println("*** " + FrenchNumberToWords.convert(28));
System.out.println("*** " + FrenchNumberToWords.convert(71));
System.out.println("*** " + FrenchNumberToWords.convert(72));
System.out.println("*** " + FrenchNumberToWords.convert(80));
System.out.println("*** " + FrenchNumberToWords.convert(81));
System.out.println("*** " + FrenchNumberToWords.convert(89));
System.out.println("*** " + FrenchNumberToWords.convert(90));
System.out.println("*** " + FrenchNumberToWords.convert(91));
System.out.println("*** " + FrenchNumberToWords.convert(97));
System.out.println("*** " + FrenchNumberToWords.convert(100));
System.out.println("*** " + FrenchNumberToWords.convert(101));
System.out.println("*** " + FrenchNumberToWords.convert(110));
System.out.println("*** " + FrenchNumberToWords.convert(120));
System.out.println("*** " + FrenchNumberToWords.convert(200));
System.out.println("*** " + FrenchNumberToWords.convert(201));
System.out.println("*** " + FrenchNumberToWords.convert(232));
System.out.println("*** " + FrenchNumberToWords.convert(999));
System.out.println("*** " + FrenchNumberToWords.convert(1000));
System.out.println("*** " + FrenchNumberToWords.convert(1001));
System.out.println("*** " + FrenchNumberToWords.convert(10000));
System.out.println("*** " + FrenchNumberToWords.convert(10001));
System.out.println("*** " + FrenchNumberToWords.convert(100000));
System.out.println("*** " + FrenchNumberToWords.convert(2000000));
System.out.println("*** " + FrenchNumberToWords.convert(3000000000L));
System.out.println("*** " + FrenchNumberToWords.convert(2147483647));
/*
*** OUTPUT
*** zéro
*** neuf
*** dix-neuf
*** vingt et un
*** vingt-huit
*** soixante et onze
*** soixante-douze
*** quatre-vingt
*** quatre-vingt-un
*** quatre-vingt-neuf
*** quatre-vingt-dix
*** quatre-vingt-onze
*** quatre-vingt-dix-sept
*** cent
*** cent un
*** cent dix
*** cent vingt
*** deux cents
*** deux cent un
*** deux cent trente-deux
*** neuf cent quatre-vingt-dix-neuf
*** mille
*** mille un
*** dix mille
*** dix mille un
*** cent mille
*** deux millions
*** trois milliards
*** deux milliards cent quarante-sept millions
** quatre cent quatre-vingt-trois mille six cent quarante-sept
*/
}
}

You can handle "dollar and cent" conversion by calling the "convert" method two times.

String phrase = "12345.67" ;
Float num = new Float( phrase ) ;
int dollars = (int)Math.floor( num ) ;
int cent = (int)Math.floor( ( num - dollars ) * 100.0f ) ;

String s = "$ " + EnglishNumberToWords.convert( dollars ) + " and "
+ EnglishNumberToWords.convert( cent ) + " cents" ;

Another way to use a built-in function of your DBMS (if available).
For Oracle

SQL> select to_char(to_date(873,'J'), 'JSP') as converted_form from dual;

CONVERTED_FORM
---------------------------
EIGHT HUNDRED SEVENTY-THREE

SQL>
'JSP' means :
J : the Julian format.
SP : spells the word for the number passed to to_date

Converting number to word

First of all take hundreds place digit by deviding by 100 and print corresponding number by calling method numberToWord((number / 100), " HUNDRED"); since number / 100 would be in between 0 to 9 so it will print digit in word concatenated by HUNDRED.

Now you left with two digit number for that you directly call numberToWord((number % 100), " "); since we are taking modulo 100 of number so it would pass two digit only. if (num > 19) {System.out.print(tens[num / 10] + " " + ones[num % 10]);} then it will take tens place and print tens word concatenated by ones. else {System.out.print(ones[num]);} directly prints word between 1 to 19 from the array.

import java.util.Scanner;

public class Test1 {



public static void main(String[] args) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
while(number!=-1){
if(number>=0 && number<=999){
if(number==0){
System.out.print("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
numberToWord(((number / 100) % 10), " HUNDRED");
numberToWord((number % 100), " ");
}

} else{
System.out.print("NUMBER OUT OF RANGE");
}
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
}
}

public static void numberToWord(int num, String val) {
String ones[] = {" ", " ONE", " TWO", " THREE", " FOUR", " FIVE", " SIX", " SEVEN", " EIGHT", " NINE", " TEN", " ELEVEN", " TWELVE", " THIRTEEN", " FOURTEEN", " FIFTEEN", " SIXTEEN", " SEVENTEEN", " EIGHTEEN", " NINETEEN"
};
String tens[] = {" ", " ", " TWENTY", " THIRTY", " FOURTY", " FIFTY", " SIXTY", " SEVENTY", " EIGHTY", " NINETY"};
if (num > 19) {
System.out.print(tens[num / 10] + " " + ones[num % 10]);
} else {
System.out.print(ones[num]);
}
if (num > 0) {
System.out.print(val);
}
}
}

Sample output:

Please type a number between 0 and 999 OR type -1 to exit:  563
NUMBER AFTER CONVERSION: FIVE HUNDRED SIXTY THREE
Please type a number between 0 and 999 OR type -1 to exit: 45
NUMBER AFTER CONVERSION: FOURTY FIVE
Please type a number between 0 and 999 OR type -1 to exit: 6
NUMBER AFTER CONVERSION: SIX
Please type a number between 0 and 999 OR type -1 to exit: 0
NUMBER AFTER CONVERSION: ZERO
Please type a number between 0 and 999 OR type -1 to exit: -1
exit

How to Convert Numbers to words

Although the code provided by kiselica-aldin will work ok, it doesn't solve most of the issues. It will also add a bug, since the last whitespace is never removed.

I've left comments to explain parts of the code.

public String numberInWords (double numbers){
String numbersAsString = String.valueOf(numbers); // "" + numbers isn't the best way of doing it
StringBuilder result = new StringBuilder(); //string builder is better that string concatenation
//we can iterate through the char list directly, no need to iterate through numbers and then access the char[] every time
for (char digit : numbersAsString.toCharArray()) {
if( digit == '0') {
result.append("zero "); //adding a trailing space, since you want them separated
continue; //what is the point of doing the other if statements if we already have a result?
}
if( digit == '1') {
result.append("one ");
continue;
}
if( digit == '2') {
result.append("two ");
continue;
}
if( digit == '3') {
result.append("three ");
continue;
}
if( digit == '4') {
result.append("four ");
continue;
}
if( digit == '5') {
result.append("five ");
continue;
}
if( digit == '6') {
result.append("six ");
continue;
}
if( digit == '7') {
result.append("seven ");
continue;
}
if( digit == '8') {
result.append("eight ");
continue;
}
if( digit == '9') {
result.append("nine ");
continue;
}
if( digit == '.') {
result.append("dot "); //or comma, or whatever, since there is a big difference between 1.25 and 125
//nothing to continue since it already is the last one
}
}
return result.toString().trim(); //trim to remove the last space
}

How to convert number to words in java- Counting money in java

When you cast a double to an int with (int), it always rounds down, no matter how close the double value is to the integer just above it. doubles cannot represent values like 186.41 exactly, because they're stored in binary instead of decimal. When you start doing lots of calculations with them, the errors start accumulating.

When I try your program, and show the value that's being rounded:

    System.out.println("result of division is " + (input/.01));
amount = (int) (input/.01);
input -= amount * .01;
System.out.println(amount + " Pennies");

it displays

    result of division is 0.999999999999658

This is very, very close to 1, so not that much error has been accumulated. But it's not exact. And since casting to (int) rounds down, amount will be 0.

There are two ways to solve this:

1) Use BigDecimal as suggested in the other answer. This is the preferred method of dealing with money. It will represent decimal places exactly.

2) Use Math.round() instead of (int), e.g.

amount = (int) Math.round(input / .01);

Math.round on a double returns a long, so you still need a cast, but it's casting from an integer to another integer so no rounding is involved.

I still recommend using BigDecimal. However, this should help you see that in other situations, where you do need to deal with double, you need to pay attention to what kind of rounding you do. Casting to (int) will often be wrong, depending on what you're trying to do.

Convert numbers to word in another way

Try this.

public static String convertViews(int n) {
if (n < 1000) return "number";
String f = String.format("%.1f",
Math.floor(n / 100) / 10).replaceAll("\\.0*$", "");
return f + "k+";
}


Related Topics



Leave a reply



Submit