Solved

Having trouble with converting numbers in java to english text.

Posted on 2004-10-10
10
290 Views
Last Modified: 2010-03-31
Hi I am a complete newbie to the java scene and I am wanting to know more about java.  Right now I am having trouble designing a simple program that will accept any double numerical value from 0.00 to 999999.99  and convert it to english text.  For example my input into my GUI would be 7856.89 and I need the out put on my GUI should come out as Seven Thousand Eight Hundred Fifty Six Dollars and 89 Cents.

the layout should look something like this of the model using these methods(only public items allowed everything else must be private), and  I have the GUI already completed:

public class MoneyModel {

public MoneyModel() */null constructor set initial value to 0.00

public double getMoneyAmount()

public void setMoneyrAmount(double)

public String getMoneyrWords()

Public static void main(String[] args) */contain test code


Your help is greatly appreciated! Thanks!

0
Comment
Question by:DreamWeaver777
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 4

Accepted Solution

by:
Rick_Townsend earned 250 total points
ID: 12271586
I don't think I've seen this question before.  See here for a good example:

http://www.rgagnon.com/javadetails/java-0426.html
0
 
LVL 9

Assisted Solution

by:DrWarezz
DrWarezz earned 250 total points
ID: 12271587
Firstly, to retrieve the number inputted into the text field, and assign it to a double, you simply do this:

public double getMoneyAmount() {
   String s = textField.getText();
   // Cast the String to a double now:
   try {
      double d = new double( s );
   } catch (Exception e) {
      return null;
   }
   return d;
}

You'd then use this to call the getMoneyAmount() method:

   double amount = getMoneyAmount();
   if ( amount == null ) {
      // An error occured.
      // The inputted value is probably not of type double.
   }

>"...should come out as Seven Thousand Eight Hundred Fifty Six Dollars and 89 Cents"
I don't know of a class that does this for you, you'd probably need to code you own algorithm to do this. :(

give me a sec, and i'll look over everything else a bit more...

gL,
[r.D]
0
 
LVL 9

Expert Comment

by:DrWarezz
ID: 12271594
Woops, change that method to:

public double getMoneyAmount() {
   String s = textField.getText();
   // Cast the String to a double now:
   double d;
   try {
      d = new double( s );
   } catch (Exception e) {
      return null;
   }
   return d;
}
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 4

Expert Comment

by:Rick_Townsend
ID: 12271595
dollars and cents are at the bottom
0
 

Author Comment

by:DreamWeaver777
ID: 12272007
here is a copy of the GUI, this may make it a little more clear:

public class MoneyGUI extends JFrame implements ActionListener {

 
   
    private MoneyModel theModel;

  /**
   * JButton to let the stuff go
   */
   private JButton goButton;

  /**
   * JTextArea to get the input from the user
   */
  private JTextArea inputArea;

  /**
   * JTextArea to show the output to the user
   */
  private JTextArea outputArea;

  /**
   * Default constructor to setup the window
   * @since 1.0
   */
  public MoneyGUI() {
    //For the application setup the window
    if (this instanceof JFrame) {
      setSize(500,200);
      setLocation(40,40);
      setTitle("Check Writer");
      setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    //Initialize instance variables
    theModel = new MoneyModel();
    goButton = new JButton("Go");
    goButton.addActionListener(this);
    inputArea = new JTextArea(1,10);
    outputArea = new JTextArea(3,40);
    outputArea.setEditable(false);
    outputArea.setLineWrap(true);
    outputArea.setWrapStyleWord(true);

    //Setup top panel
    JPanel topPanel = new JPanel();
    JLabel numLabel = new JLabel("Number to translate: ");
    topPanel.add(numLabel);
    topPanel.add(inputArea);    

    //Setup center panel
    JPanel centerPanel = new JPanel();
    JLabel outLabel = new JLabel("Number as text: ");
    centerPanel.add(outLabel);
    centerPanel.add(outputArea);
   
    this.getContentPane().add(topPanel,BorderLayout.NORTH);
    this.getContentPane().add(centerPanel,BorderLayout.CENTER);
    this.getContentPane().add(goButton,BorderLayout.SOUTH);
  }

  public void actionPerformed (ActionEvent e) {
    try {
      String inText = inputArea.getText();
      double inValue = Double.parseDouble(inText);
      theModel.setCheckAmount(inValue);
      outputArea.setText(theModel.getMoneyWords());
    }
    catch (NumberFormatException except) {
      outputArea.setText("You have input a non-numeric value");
      inputArea.setText("");
    }
  }

  /**
   * Main method to get stuff started
   * @since 1.0
   */
  public static void main (String args[]) {
    MoneyGUI myGUI = new MoneyGUI();
    myGUI.show();
  }
}
0
 
LVL 9

Expert Comment

by:DrWarezz
ID: 12272130
:o\ hmm... the Class "MoneyModel", is that a personal class? or have you downloaded an API? Because, I don't know of this class, and my compiler won't compile your program because of it..

[r.D]
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 12272721
Hrmmm... I'm sorry to say that you may have to do it manually and it won't be a fun class to write. :(

You'll have to have a class to check which numbers are located in what digits. This is probably done best by converting your double to a String. Then you can use String.charAt(0) (for the first digit) and String.length() to help you figure out where things are. Then you'll just have to make all the '7's into "Sevens" and '5's into "Fives", etc. Note that you'll need to do something special for all the "teen" numbers. (i.e., if the second to last integer digit is a 1, check whether the last digit, is one, two, three, etc. and print out, eleven, twelve, thirteen, etc.). Besides that you just check where the digit is and tack on the unit i.e. if the digit is the first of 4 integer digits, tack on "Thousand". Good luck!
0
 
LVL 4

Expert Comment

by:Rick_Townsend
ID: 12272930
Follow the link in my first comment.  That is how to generate English (and French) names of numbers.

"Don't re-invent the wheel when you can borrow one from your neighbour."
0
 

Author Comment

by:DreamWeaver777
ID: 12273019
Hey guys I really appreciate your comments and suggestions ya'll have been an enormous help.  I just have one more last thing to ask about this.
Can anybody give me any suggestions on how to implement this code that I have into each of my methods? (Thanks for the page Rick)

methods:
public class MoneyModel {

public MoneyModel() */null constructor set initial value to 0.00

public double getMoneyAmount()

public void setMoneyrAmount(double)

public String getMoneyrWords()

Public static void main(String[] args) */contain test code

code:(I know I will have to change my class names)
class EnglishDecimalFormat {
  private static final String[] majorNames = {
    "",
    " Thousand",
    " million",
    " billion",
    " trillion",
    " quadrillion",
    " quintillion"
    };

  private static final String[] tensNames = {
    "",
    " Ten",
    " Twenty",
    " Thirty",
    " Fourty",
    " 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 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 String convert(int number) {
    /* special case */
    if (number == 0) { return "zero"; }

    String prefix = "";

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

    String soFar = "";
    int place = 0;

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

    return (prefix + soFar).trim();
}
 


public static void main(String[] args) {
    EnglishDecimalFormat f = new EnglishDecimalFormat();
    System.out.println("*** " + f.convert(6));
    System.out.println("*** " + f.convert(9));
    System.out.println("*** " + f.convert(16));
    System.out.println("*** " + f.convert(100));
    System.out.println("*** " + f.convert(118));
    System.out.println("*** " + f.convert(200));
    System.out.println("*** " + f.convert(219));
    System.out.println("*** " + f.convert(800));
    System.out.println("*** " + f.convert(801));
    System.out.println("*** " + f.convert(1316));
    System.out.println("*** " + f.convert(1000000));
    System.out.println("*** " + f.convert(2000000));
    System.out.println("*** " + f.convert(3000200));
    System.out.println("*** " + f.convert(700000));
    System.out.println("*** " + f.convert(9000000));
    System.out.println("*** " + f.convert(123456789));
    System.out.println("*** " + f.convert(-45));
    /*
    *** 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 million
    *** three million two hundred
    *** seven hundred thousand
    *** nine million
    *** one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine
    *** negative fourty five
    */
    }
}


Thanks  again Rick, DrWarezz, and CI-Ia0s
0
 
LVL 9

Expert Comment

by:DrWarezz
ID: 12278029
8-) ThanQ
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question