Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Simple CashRegister program behaviour issue [Basic]

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Simple CashRegister program behaviour issue [Basic]

    Hello,

    I am writing a simple Java code, which acts like a Cash Register, However I have faced an issue which I hope to get some help on.

    The program:

     
    public class TestItem
    {
     
     
      private double Order;   // instant variable which will be representing the item's price
      private double Paid;   // Paid is an instant variable which represent the amount paid for the item
     
    /**
     * Constructs a Cash Register with zero values
     */
      public TestItem()
      {
          Order = 0;
          Paid = 0;
        }
     
    /**
     * Initiating the price of the item ordered in the cash register
     * @param total is the price of the item
     */   
        public void recordOrder(double total)
        {
            this.Order = Order + total;
        }
     
    /**
    * Deposit the amount paid by the costumer to the cash registrer
    * @param dollars is the amount paid
    */
        public void enterPaidValue(double dollars)
        {
            Paid = dollars;
     
        }
     
    /**
     * Calculate then return the change to the cosutmer
     */   
        public double giveChange()
        {
     
            double change = Paid - Order;    
            Order = 0;  // after the calculation is done, reset the register value, ready to serve a new costumer
            Paid = 0;   // after the calculation is done, reset the register value, ready to serve a new costumer[/COLOR]
            return change;  // return the change
     
        }
    }


    Well yes it is easy as it looks, now after coding the tester program:
    /**
     * This class is a tester class
     */
     
    public class TestItemTester
    {
    /**
     * Main method.
     */
      public static void main(String[] args)
    {
     
       TestItem register = new TestItem();  // creating a new object of the class TestItem
       register.recordOrder(19.93);        // calling the method recordOrder and initiating parameters, this is
                                           // the cost of the Item.
       register.enterPaidValue(20);       // calling the method enterPaidValue, initiating parameter, this is 
                                           // the amount that the costumer have paid.[/COL
     
       System.out.print("Change: ");     
       System.out.println(register.giveChange());  // calling giveChange method to pring out the change.
    }
     
    }

    Everything is going smooth, except of the result of giveChange() method, after calling giveChange() method the result turns out to be: "Change: 0.07000000000000028", I know this is happening becuase of the behaviour of the primitive type "double", which is basicly occuring the (rounding error).

    I am trying to result a better output, like "0.07" instead of "0.07000000000000028" as this will confuse the cashier, any thoughts?

    Regards,


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simple CashRegister program behaviour issue [Basic]

    Do a google search of an article called "what every computer scientist should know about floating point arithmetic". Read it.

    You shouldn't use floats (or doubles) for currency. Use an int and count the smallest unit (pennies) then figure it out from there.

    You could also use a class like DecimalFormat.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Jun 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Simple CashRegister program behaviour issue [Basic]

    Quote Originally Posted by KevinWorkman View Post
    Do a google search of an article called "what every computer scientist should know about floating point arithmetic". Read it.

    You shouldn't use floats (or doubles) for currency. Use an int and count the smallest unit (pennies) then figure it out from there.

    You could also use a class like DecimalFormat.
    I was asked to use double, thanks anyway.

    PS: having a rough day?

  4. #4
    Member
    Join Date
    Apr 2012
    Posts
    161
    Thanks
    0
    Thanked 27 Times in 27 Posts

    Default Re: Simple CashRegister program behaviour issue [Basic]

    I found a very useful website that has a lot of information about formatting what you want to print out. There is specifically a section about formatting floating point numbers, which you should find very helpful Enjoy

    A printf format reference page (cheat sheet) | printf reference for java perl ruby | devdaily.com

  5. #5
    Junior Member
    Join Date
    Jun 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Simple CashRegister program behaviour issue [Basic]

    Quote Originally Posted by Parranoia View Post
    I found a very useful website that has a lot of information about formatting what you want to print out. There is specifically a section about formatting floating point numbers, which you should find very helpful Enjoy

    A printf format reference page (cheat sheet) | printf reference for java perl ruby | devdaily.com
    You sir, are a life saver , this is the kind of solution I was looking for, I edited the last line in the TestItemTester class as follows:

    System.out.printf("%8.2f", register.giveChange());

    output results: 0.07

    Thank you very much you provided me a 2 minutes solution

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Simple CashRegister program behaviour issue [Basic]

    Quote Originally Posted by Moa View Post
    I was asked to use double, thanks anyway.

    PS: having a rough day?
    I was not having a rough day, and I was not trying to be rude. That article is required reading for every programmer.

    DecimalFormat would have given you a similar 2-minute solution had you consulted the API, but at least you got a solution figured out.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Junior Member
    Join Date
    Jun 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Simple CashRegister program behaviour issue [Basic]

    Quote Originally Posted by KevinWorkman View Post
    I was not having a rough day, and I was not trying to be rude. That article is required reading for every programmer.

    DecimalFormat would have given you a similar 2-minute solution had you consulted the API, but at least you got a solution figured out.
    I am actually giving the DecimalFormat a go too, and thanks for opening my eyes on that article, great stuff.
    Last edited by Moa; June 19th, 2012 at 03:53 PM.

Similar Threads

  1. Quicksort algorithm displaying strange behaviour
    By Mathew.Williams in forum What's Wrong With My Code?
    Replies: 0
    Last Post: April 19th, 2011, 12:56 PM
  2. [SOLVED] Java Network simple issue
    By Budlee in forum Java Networking
    Replies: 2
    Last Post: April 7th, 2011, 12:49 PM
  3. Basic loop issue
    By Nismoz3255 in forum Loops & Control Statements
    Replies: 3
    Last Post: February 23rd, 2011, 05:10 PM
  4. CashRegister class- adding a method getItemCount
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: January 21st, 2010, 08:29 PM
  5. Swing incorrect behaviour from JRE5 to JRE6
    By singhkanhaiya in forum AWT / Java Swing
    Replies: 1
    Last Post: August 25th, 2009, 01:23 AM