Taba
Taba

Reputation: 133

ANDROID: Converting inputted numbers to words

Our assignment states that we write a program that will input a number up to 6 digits and will convert the numbers into words.. ex: 123 = one hundred twenty three. I AM CLUELESS! Then I found this site http://www.rgagnon.com/javadetails/java-0426.html but I don't really understand how to convert it into android.

please help me..please.

here is my Main_Activity.xml:

package com.example.torres;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

    final EditText numbers =  (EditText) findViewById(R.id.editText1);
    final EditText results = (EditText) findViewById(R.id.editText2);

    Button btnConvert = (Button) findViewById(R.id.button1);     
    btnConvert.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
         String numberz =numbers.getText().toString();
         try {
             final long number = Long.parseLong(numberz);
             String returnz = Words.convert(number); 
         } catch ( NumberFormatException e) {
             //Toast.makeToast("illegal number or empty number" , toast.long)
         }

                       }  });


        }}

and here is my Words.java

package com.example.torres;

import java.text.DecimalFormat;

public class Words  {




      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 Words() {}


    public 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", " ");}




      }

The only problem now is that nothing happens lol

Upvotes: 8

Views: 18782

Answers (5)

Chirag Solanki
Chirag Solanki

Reputation: 1277

Above all the solution is working fine, Only problem is that this is not working for all language because all country is not having the same set of rules to convert a number into word so we need to write a separate algorithm for each country,

Solution

ICU4J is an international Unicode component library that is allowed so many utilities regarding language translation follow below steps.

  • Step 1 Add ICU4J in your app level gradle like below
    dependencies {
        implementation group: 'com.ibm.icu', name: 'icu4j', version: '51.1' 
    }
    
  • Step 2 Define this method
    private String convertIntoWords(Double str,String language,String Country) {
          Locale local = new Locale(language, Country);
          RuleBasedNumberFormat ruleBasedNumberFormat = new RuleBasedNumberFormat(local, RuleBasedNumberFormat.SPELLOUT);
          return ruleBasedNumberFormat.format(str);
    }
    
  • Step 3 Now you can call this method like below
    double value=165;
    String english=convertIntoWords(value,"en","US"); //one hundred and sixty-five
    /*Peruvion*/
    String Spanish=convertIntoWords(value,"es","PE"); //ciento sesenta y cinco
    

You can change language and country based on your requirements.

Upvotes: 6

nglauber
nglauber

Reputation: 23864

Posting my answer here because can be helpful to someone else...

import android.icu.text.MessageFormat
import java.util.Locale

fun Double.toWords(language: String, country: String): String {
    val formatter = MessageFormat(
        "{0,spellout,currency}", 
        Locale(language, country)
    )
    return formatter.format(arrayOf(this))
}

and you can use it like this:

import androidx.compose.ui.text.intl.Locale

// ...

(12345678.99).toWords(Locale.current.language, Locale.current.region)

// OR,

(12345678.99).toWords("en", "US") // For static local

This call will return the string

twelve million three hundred forty-five thousand six hundred seventy-eight point nine nine

Reference: https://developer.android.com/reference/android/icu/text/MessageFormat

Upvotes: 9

MohK
MohK

Reputation: 1933

You can make separate class for EnglishNumberToWords as in the example link.

and in your button click you have to just call

String return_val_in_english =   EnglishNumberToWords.convert(YOUR_NUMBER_TO_CONVERT);

enter image description here

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 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", " ");
}

}

Upvotes: 16

Siva Prasad
Siva Prasad

Reputation: 125

Java Class for that :-

public class NumberToWordsConverter {

        public static final String[] units = {"", "One", "Two", "Three", "Four",
                "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
                "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
                "Eighteen", "Nineteen"};

        public static final String[] tens = {
                "",        // 0
                "",        // 1
                "Twenty",    // 2
                "Thirty",    // 3
                "Forty",    // 4
                "Fifty",    // 5
                "Sixty",    // 6
                "Seventy",    // 7
                "Eighty",    // 8
                "Ninety"    // 9
        };

        public static String convert(final int n) {
            if (n < 0) {
                return "Minus " + convert(-n);
            }

            if (n < 20) {
                return units[n];
            }

            if (n < 100) {
                return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
            }

            if (n < 1000) {
                return units[n / 100] + " Hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
            }

            if (n < 100000) {
                return convert(n / 1000) + " Thousand" + ((n % 10000 != 0) ? " " : "") + convert(n % 1000);
            }

            if (n < 10000000) {
                return convert(n / 100000) + " Lakh" + ((n % 100000 != 0) ? " " : "") + convert(n % 100000);
            }

            return convert(n / 10000000) + " Crore" + ((n % 10000000 != 0) ? " " : "") + convert(n % 10000000);
        }
    }

Implementation in your main class. You can have separate method like the follwing or you can directly use without separate method.

private String numToWords (int n){ //optional
        NumberToWordsConverter ntw = new NumberToWordsConverter(); // directly implement this
        return ntw.convert(n);
    } //optional

Upvotes: 2

Mudasar
Mudasar

Reputation: 159

You have done all the work just display String returnz in a text field like this

 results.setText(returnz);

Upvotes: -3

Related Questions