Solved

Having trouble with converting numbers in java to english text.

Posted on 2004-10-10
10
294 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 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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 
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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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 “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

691 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