?
Solved

Having trouble with converting numbers in java to english text.

Posted on 2004-10-10
10
Medium Priority
?
297 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 4

Accepted Solution

by:
Rick_Townsend earned 750 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 750 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month13 days, 7 hours left to enroll

801 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