Solved

How to calculate currency values

Posted on 1998-07-27
14
912 Views
Last Modified: 2010-03-30
Could you please help me write a application program to do the following task?
1.    Set the value of the TextField txtFeeOwed to $10.50.
2.    After the user enter the value of the TextField txtFeePaid, calculate  
       the FeeBalance (= FeePaid - FeeOwed), and set the result to the
       TextField txtFeeBalance.




0
Comment
Question by:leeann
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 2

Expert Comment

by:threshold
ID: 1228479
Test7.java :

class Test7 extends java.awt.Frame implements java.awt.event.TextListener, java.awt.event.WindowListener {
      private java.awt.Label LBalance = null;
      private java.awt.Label LOwed = null;
      private java.awt.Label LPaid = null;
      private java.awt.TextField TBalance = null;
      private java.awt.TextField TOwed = null;
      private java.awt.TextField TPaid = null;

public Test7() {
      super();
      initialize();
}

public Test7(String title) {
      super(title);
}
private java.awt.Label getlBalance() {
      if (LBalance == null) {
            LBalance = new java.awt.Label();
            LBalance.setName("lBalance");
            LBalance.setText("Balance");
            LBalance.setBounds(13, 168, 54, 33);
      };
      return LBalance;
}

private java.awt.Label getlOwed() {
      if (LOwed == null) {
            LOwed = new java.awt.Label();
            LOwed.setName("lOwed");
            LOwed.setText("Owed");
            LOwed.setBounds(13, 34, 54, 33);
      }      
      return LOwed;
}

private java.awt.Label getlPaid() {
      if (LPaid == null) {
            LPaid = new java.awt.Label();
            LPaid.setName("lPaid");
            LPaid.setText("Paid");
            LPaid.setBounds(13, 101, 54, 33);
      }      
      return LPaid;
}

private java.awt.TextField getTBalance() {
      if (TBalance == null) {
            TBalance = new java.awt.TextField();
            TBalance.setName("TBalance");
            TBalance.setText("0");
            TBalance.setBounds(81, 171, 125, 30);
      }      
      return TBalance;
}

private java.awt.TextField getTOwed() {
      if (TOwed == null) {
            TOwed = new java.awt.TextField();
            TOwed.setName("TOwed");
            TOwed.setText("0");
            TOwed.setBounds(81, 37, 125, 30);
      }
      return TOwed;
}

private java.awt.TextField getTPaid() {
      if (TPaid == null) {
                  TPaid = new java.awt.TextField();
                  TPaid.setName("TPaid");
                  TPaid.setText("0");
                  TPaid.setBounds(82, 104, 125, 30);
      }
      return TPaid;
}

private void ifChanged( ) {
      try {
            double paid=(new Double(getTPaid().getText())).doubleValue();
            double owed=(new Double(getTOwed().getText())).doubleValue();
            getTBalance().setText(""+(paid-owed));
      }      catch(Exception e) {
            getTBalance().setText("ERR:"+e.getMessage());
      }      
}
private void initConnections() {
      this.addWindowListener(this);
      getTOwed().addTextListener(this);
      getTPaid().addTextListener(this);
}

private void initialize() {
      setName("Test7");
      setName("Test7");
      setLayout(null);
      setSize(224, 235);
      add(getlOwed(), getlOwed().getName());
      add(getlPaid(), getlPaid().getName());
      add(getlBalance(), getlBalance().getName());
      add(getTOwed(), getTOwed().getName());
      add(getTPaid(), getTPaid().getName());
      add(getTBalance(), getTBalance().getName());
      initConnections();
}

/**
 * main entrypoint - starts the part when it is run as an application
 * @param args java.lang.String[]
 */
public static void main(java.lang.String[] args) {
            Test7 aTest7 = new Test7();
            aTest7.setVisible(true);
}

public void textValueChanged(java.awt.event.TextEvent e) {
      if ((e.getSource() == getTOwed()) ) {
            this.ifChanged();
      }
      if ((e.getSource() == getTPaid()) ) {
            this.ifChanged();
      }
}

public void windowActivated(java.awt.event.WindowEvent e) {
}

public void windowClosed(java.awt.event.WindowEvent e) {
}

public void windowClosing(java.awt.event.WindowEvent e) {
      if ((e.getSource() == this) ) {
            this.dispose();
      }
}

public void windowDeactivated(java.awt.event.WindowEvent e) {
}

public void windowDeiconified(java.awt.event.WindowEvent e) {
}

public void windowIconified(java.awt.event.WindowEvent e) {
}

public void windowOpened(java.awt.event.WindowEvent e) {
}

}
0
 

Author Comment

by:leeann
ID: 1228480
Hi, Threshold:
Thanks for your time. I have tested your code. Here are some problems:
1.    The values in the TextFields are not integers. They are currency.
       Your code didn't allow me to enter "$10.0" in the text  field.
       Also, it can not calculate "$10.0 - $9.50".
2.    The result can not be 5.9999999.( Should be $6.00 ).
0
 

Author Comment

by:leeann
ID: 1228481
Adjusted points to 40
0
 
LVL 4

Expert Comment

by:evijay
ID: 1228482
replace the below line

getTBalance().setText(""+(paid-owed));

with

DecimalFormat df = new DecimalFormat("########.##");
getTBalance().setText(df.format(paid-owed));



be sure to include in the beginning of the program

import java.text.*;


Be sure to give the points to threshold since he has given the complete answer

0
 
LVL 2

Expert Comment

by:sprinkmeier
ID: 1228483
_NEVER_ use floating point for money!
Always store the result in cent (or whatever the base unit is) and convert when displaying, using ONLY integer math!
Did you know that floating point numbers cannot accuratley store the value 1.2 ?
0
 

Author Comment

by:leeann
ID: 1228484
Dear frields, thanks for your help!
But my problem still can not be solved. Because in my database, the domains of the
FeeOwed, FeePaid, and FeeBalance are Currency, not double. I don't know how to
convert a "double" into" Currency($)"? Could you please help me to fix it?
0
 
LVL 2

Expert Comment

by:threshold
ID: 1228485
You can use double as currency carefully, 'cause there are some problem in calculation of double.

Here is the code I fixed:

private void ifChanged( ) {
try {
   String paid=getTPaid().getText();
   String owed=getTOwed().getText();
   int c=-1;
   while ((c=paid.indexOf("$"))!=-1) paid=paid.substring(0,c)+paid.substring(c+1); // skip the '$'
   while ((c=owed.indexOf("$"))!=-1) paid=owed.substring(0,c)+owed.substring(c+1); // skip the '$'
       
   double paid=(new Double(paid.getText())).doubleValue(); // convert it into double
   double owed=(new Double(owed.getText())).doubleValue();
   DecimalFormat f=new DecimalFormat("##################.00"); // choose a format
   getTBalance().setText(f.format(paid-owed+0.005)); // display it with the format, it will display the 'neighborhood' of the result
} catch(Exception e) {
   getTBalance().setText("ERR:"+e.getMessage());
}
}
or you want to get the 'flood' of the result:

   double p="0.000000001"; // p is the suitable precision factor
   getTBalance().setText(f.format(paid-owed+p));

And, It's not easy to calculate "expression" like "1+2*(3+4.5)" in Java. If you have to do this, here are 2 ways I tried:
1. In Java Application, create a .java file that include a simple class which contains the expression.
    example of the .java file:
        public class myTemp {
            public static double calc() {
                return 1.0+3.5*(55+3);          // place your expression after 'return'
            }
        }
    Then, use the Runtime.exec("javac xxx.java") to compile the .java file dynamically.
    And check the exit code ,then use the myTemp.calc() to get the double result.

2. In Applet, you have to write many code to parse the expression and calculate it, it's not a simple program if you want it works with +,-,*,/,sin(...),cos(...),...or every functions you want.

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 2

Expert Comment

by:threshold
ID: 1228486
Maybe,sprinkmeier is right.

We should use BigDecimal to store Money...
0
 
LVL 2

Expert Comment

by:threshold
ID: 1228487
Oh, you want to get currency data from/into database...

There is RecordSet.getDouble("...") or RecordSet.getBigDecimal("...") for reading

and Statement.excuteQuery("update myTable set MyMoney="+myDouble)

or Statement.excuteQuery("update myTable setMyMoney="+myBigDecimal)

Is it the stuff you want?
0
 

Author Comment

by:leeann
ID: 1228488
Hi, threshold:
I tested your fixed program and got six error messages. You double defined variables
"paid" and "owed" ( String and double ).
You are right. I want to get currency data from/into database. If you can help me to fix
it, it would be very nice.
Thanks a lot!

         
0
 
LVL 2

Expert Comment

by:sprinkmeier
ID: 1228489
You might find that Currency($) is an integer (storing cents or something) that is just displayed/parsed to look like  afloat (ie. $19.95). If your DB is really smart, it might even adjust the currency for local conventions (like displaying data/time in 12/24 hours, YYYYMDD vs. MMDDYYYY etc.).
The best thing is probably still to work with it as an integer. converting to/from Currency($) could be done using a laot type of some sort, that should be save enough.

FYI, try

float i = 1;
while(true)
{
  i += 0.2;
  i += 0.2;
  i += 0.2;
  i += 0.2;
  i += 0.2;
  i -= 1;
  System.out.println(i);
}
0
 

Author Comment

by:leeann
ID: 1228490
Hi, threshold:
I'm looking forward to seeing your fixed codes. Have you done it?
0
 

Author Comment

by:leeann
ID: 1228491
points for threshold
0
 
LVL 2

Accepted Solution

by:
threshold earned 40 total points
ID: 1228492
Sorry...

private void ifChanged( ) {
               try {
                  String paid=getTPaid().getText();
                  String owed=getTOwed().getText();
                  int c=-1;
                  while ((c=paid.indexOf("$"))!=-1) paid=paid.substring(0,c)+paid.substring(c+1); // skip the '$'
                  while ((c=owed.indexOf("$"))!=-1) paid=owed.substring(0,c)+owed.substring(c+1); // skip the '$'
                  try {
                      double dpaid=(new Double(paid)).doubleValue(); // convert it into double
                      double dowed=(new Double(owed)).doubleValue();
                  } catch (NumberFormatException e)
                      getTBalance().setText("Error");
                      return;
                  }
                  DecimalFormat f=new DecimalFormat("##################.00"); // choose a format
                  getTBalance().setText(f.format(dpaid-dowed+0.005)); // display it with the format, it will display the 'neighborhood'
               of the result
               } catch(Exception e) {
                  getTBalance().setText("ERR:"+e.getMessage());
               }
               }
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now