Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 961
  • Last Modified:

How to calculate currency values

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
leeann
Asked:
leeann
  • 6
  • 5
  • 2
  • +1
1 Solution
 
thresholdCommented:
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
 
leeannAuthor Commented:
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
 
leeannAuthor Commented:
Adjusted points to 40
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
evijayCommented:
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
 
sprinkmeierCommented:
_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
 
leeannAuthor Commented:
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
 
thresholdCommented:
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
 
thresholdCommented:
Maybe,sprinkmeier is right.

We should use BigDecimal to store Money...
0
 
thresholdCommented:
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
 
leeannAuthor Commented:
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
 
sprinkmeierCommented:
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
 
leeannAuthor Commented:
Hi, threshold:
I'm looking forward to seeing your fixed codes. Have you done it?
0
 
leeannAuthor Commented:
points for threshold
0
 
thresholdCommented:
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 5
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now