We help IT Professionals succeed at work.

How to calculate currency values

leeann asked
Medium Priority
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.

Watch Question

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() {

public Test7(String title) {
private java.awt.Label getlBalance() {
      if (LBalance == null) {
            LBalance = new java.awt.Label();
            LBalance.setBounds(13, 168, 54, 33);
      return LBalance;

private java.awt.Label getlOwed() {
      if (LOwed == null) {
            LOwed = new java.awt.Label();
            LOwed.setBounds(13, 34, 54, 33);
      return LOwed;

private java.awt.Label getlPaid() {
      if (LPaid == null) {
            LPaid = new java.awt.Label();
            LPaid.setBounds(13, 101, 54, 33);
      return LPaid;

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

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

private java.awt.TextField getTPaid() {
      if (TPaid == null) {
                  TPaid = new java.awt.TextField();
                  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();
      }      catch(Exception e) {
private void initConnections() {

private void initialize() {
      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());

 * 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();

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

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) ) {

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) {



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 ).


Adjusted points to 40

replace the below line



DecimalFormat df = new DecimalFormat("########.##");

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

_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 ?


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?
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) {
or you want to get the 'flood' of the result:

   double p="0.000000001"; // p is the suitable precision factor

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.

Maybe,sprinkmeier is right.

We should use BigDecimal to store Money...
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?


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!

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;
  i += 0.2;
  i += 0.2;
  i += 0.2;
  i += 0.2;
  i += 0.2;
  i -= 1;


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


points for threshold
Unlock this solution and get a sample of our free trial.
(No credit card required)
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.