Solved

how to subtract decimal????

Posted on 2002-05-27
15
351 Views
Last Modified: 2008-02-26
hi guys!!!!

i had a program that subtract two double variable.here's my code:



import java.awt.*;
import java.awt.event.*;

public class Try
{

        public static void main(String argv[])
    {
            Frame fr = new Frame();
            fr.pack();
            fr.setVisible(true);

            Panel panel = new Panel();

            final TextField tf1 = new TextField(15);
            final TextField tf2 = new TextField(15);

            final Button subtract = new Button("Minus");
            Button clear = new Button("Clear");
            subtract.addActionListener(new ActionListener()
            {
               public void actionPerformed(ActionEvent e)
               {
                         if (e.getSource() == subtract)
                         {
                              double a = new Double(tf1.getText()).doubleValue();
                              double b = new Double(tf2.getText()).doubleValue();

                              System.out.println(a-b);
                         }
               }

          });

            panel.add(tf1);
            panel.add(tf2);
            panel.add(subtract);
            panel.add(clear);

            fr.add(panel);
       }//End of main

       }


OUTPUT:

TF1 = 50.56
TF2 = 25
DIFFERENCE = 25.560000000000002


how would i make it so that it will only return 25.26???

thanks in advance!!!




0
Comment
Question by:rdy1437
  • 7
  • 4
  • 3
  • +1
15 Comments
 
LVL 92

Expert Comment

by:objects
Comment Utility
That's simply a rounding error resulting from floating point arithmetic. If you need to avoid this then use the BigDecimal class, or simply format your output to two decimal places.
0
 

Author Comment

by:rdy1437
Comment Utility
can you provide sample code for this??
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
BigDecimal a = new BigDecimal("50.56");
BigDecimal b = new BigDecimal("25");
BigDecimal c = a.subtract(b);
System.out.println(c);


0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Floating point numbers are only an approximation (albeit quite an accurate one).
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
 There is also an excellent tutorial on BigDecimal: http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html
0
 
LVL 2

Expert Comment

by:vogen
Comment Utility
// rdy1437, here is the solution:

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

public class Try
{
     public static void main(String argv[])
  {
       Frame fr = new Frame();
    fr.pack();
    fr.setVisible(true);
    Panel panel = new Panel();

    final TextField tf1 = new TextField(15);
    final TextField tf2 = new TextField(15);

    final Button subtract = new Button("Minus");
    Button clear = new Button("Clear");
    subtract.addActionListener(new ActionListener()
    {
     public void actionPerformed(ActionEvent e)
     {
      DecimalFormat twoDigits = new DecimalFormat( "0.00" );
      if (e.getSource() == subtract)
      {
        double a = new Double(tf1.getText()).doubleValue();
        double b = new Double(tf2.getText()).doubleValue();
                 double result =(double) a - (double) b;
                    System.out.println( twoDigits.format(result) );
      }
   }
   });
   panel.add(tf1);
   panel.add(tf2);
   panel.add(subtract);
   panel.add(clear);
   fr.add(panel);
   }//End of main
}
0
 
LVL 2

Expert Comment

by:vogen
Comment Utility
DecimalFormat object that is initialized with the string "0.00". Each 0 is a format flag that specifies a required digit position in the formatted floating-point number.

pls ask if have any question..

cheers
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 92

Expert Comment

by:objects
Comment Utility
vogen,

1. Please avoid proposing answers as it locks the question and make it harder for other experts to contribute.

2. I had already suggested the option of using formatting.
0
 

Author Comment

by:rdy1437
Comment Utility
thanks guys for your comments.i already used the comment made by objects...
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Good to hear it helped :-)
Can you accept my comment as an answer then please.
0
 
LVL 2

Expert Comment

by:vogen
Comment Utility
solly, i was only trying to help.. ::(
0
 

Author Comment

by:rdy1437
Comment Utility
hey objects how can i give you the points?
0
 
LVL 92

Accepted Solution

by:
objects earned 50 total points
Comment Utility
reject the proposed answer, and accept my comment as an answer :)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
0
 
LVL 2

Expert Comment

by:vogen
Comment Utility
I spent my time and this is what I get
it's not fair
thanks anyway
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
hash value 2 38
Running Jira on Raspberry PI 2? 3 117
base64 decode encode 12 94
compre toata in where clue oracle 4 41
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
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…
The viewer will learn how to implement Singleton Design Pattern in Java.

762 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

10 Experts available now in Live!

Get 1:1 Help Now