We help IT Professionals succeed at work.

# How to calculate currency values

on
Medium Priority
974 Views
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.

Comment
Watch Question

## View Solution Only

Commented:
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);
}
}

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

private void initialize() {
setName("Test7");
setName("Test7");
setLayout(null);
setSize(224, 235);
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) {
}

}

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

Commented:

Commented:
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

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

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

Commented:
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.

Commented:
Maybe,sprinkmeier is right.

We should use BigDecimal to store Money...

Commented:
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?

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!

Commented:
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);
}

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

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