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.

Page 1 of 2 12 LastLast
Results 1 to 25 of 28

Thread: Formatting answers to 2 decimal places

  1. #1
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Formatting answers to 2 decimal places

    Hello all,

    I've been scanning forums for answers to this problem, but most deal with simple programming that you might find in a classroom (i.e. "System.out.printf") which will not work in the GUI I'm attempting to complete. Here's the tale of the tape:

    The GUI is a price calculator I'm developing for my company that takes input from drop-down menus and several Jtextfields and calculates the answer based on the values contained within each. It's completely done (and thankfully functional), so I'd rather not change too much if at all possible. Because I'm dealing with decimal values then I'm getting 9 decimal places in the output JLabel, though. In order to display the answer, I'm using a series of "totalPrice.setText(..." declarations.

    Because there is a fair amount of text and the values in the calculation are constantly changing, is there a way to 'simply' format the output JLabel to display only 2 decimals? Or is there an alternative solution that would work--say with a JTextfield instead--without having to completely re-code the calculator?
    Last edited by Cal S.; September 8th, 2014 at 03:20 PM.


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Formatting answers to 2 decimal places

    The JLabel needs a string to display anyways. So at some point you create a string from your numbers. At this point simply cut-off the last parts of the string until you get 2 decimals behind the floating point.

    This is an example of how you could do it:
    		String numAsStr = "123.4567";
    		// -1 if there is no floating point in the number
    		int pointIndex = numAsStr.lastIndexOf('.');
    		String numFormatted = numAsStr;
    		// Check if we can cut off last digits until floating point.
    		// Only possible if there is a floating point, and there are more then 2 digits after the floating point
    		if (pointIndex != -1 && numAsStr.length() >= pointIndex + 3) {
    			// Cut the last digits off
    			numFormatted = numAsStr.substring(0, pointIndex + 3);
    		}
    		System.out.println(numFormatted);

  3. #3
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Thank you for the quick response! Maybe I'm a little newer than I thought. I just edited my question after you answered, so I apologize for that, but here's a snippet of my declarations:

    "totalPrice" is my JLabel

    if(materialDropDown.getSelectedIndex()==0) totalPrice.setText("The price is: $"
    + ((0.098*number2*number3*number4)*3.06));
    else if(materialDropDown.getSelectedIndex()==1) totalPrice.setText("The price is: $"
    + ((0.1*number2*number3*number4)*5.61));

    And on it goes until I get to ()==18, and then I repeat the series for cylindrical portions. Any way to sneak what you suggested into that? I seem to remember from my Visual Basic days a somewhat simpler way of doing this...
    Last edited by Cal S.; September 8th, 2014 at 03:33 PM.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    Make a method that does the computations. Put the constant data in a collection (or 2 dim array) that is accessed by the selected index.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Quote Originally Posted by Norm View Post
    Make a method that does the computations. Put the constant data in a collection (or 2 dim array) that is accessed by the selected index.
    Not sure exactly how to do that.

    Also, because I'm multiplying and inputting decimal numbers I cannot use 'int' variable, I have to use 'double' or 'float'. However, now that I've done that, the code is only half working. There are two sections, one for a rectangular portion and the other for a cylindrical portion.

    If you could help me troubleshoot the following, I'd be eternally grateful:

    double number1, number2, number3, number4;
    // Make sure numbers entered are whole numbers
    try {
    number1 = Double.parseDouble(
    this.diameterBox.getText());
    number2 = Double.parseDouble(
    this.lengthBox.getText());
    number3 = Double.parseDouble(
    this.heightBox.getText());
    number4 = Double.parseDouble(
    this.widthBox.getText());
    }
    catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Must be a whole number",
    "Error", JOptionPane.ERROR_MESSAGE);
    return;
    }
    //My attempt at formatting the decimals (not working so well):
    DecimalFormat currencyFormat = new DecimalFormat("#, ###.##");

    //Rectangle portion (not-working):
    if(materialDropDown.getSelectedIndex()==0) totalPrice.setText("The price is: $"
    + ((0.098*(number2*number3*number4)*3.06)));
    else if(materialDropDown.getSelectedIndex()==1) totalPrice.setText("The price is: $"
    + ((0.1*number2*number3*number4)*5.61));

    //Cylinder portion (working fine):
    if(materialDropDown.getSelectedIndex()==0) totalPrice.setText("The price is: $"
    + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06));
    //2024
    else if(materialDropDown.getSelectedIndex()==1) totalPrice.setText("The price is: $"
    + ((0.1*(((number1/2)*(number1/2))*3.14159*number2))*5.61));

    And so on. If you're wondering why I didn't just square (number1/2), it's because that produced errors.

    Again, this is a fairly advanced GUI that accepts user inputs, so there are no System.out.print statements that I could use.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE GOES HERE
    [/code]
    to get highlighting and preserve formatting.

    help me troubleshoot the following,
    Can you post the program's output, explain what is wrong with it and post an example of what the output should be.

    BTW The code would be easier to read if the statements were on separate lines.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Like this?

    double number1, number2, number3, number4;
    // Make sure numbers entered are whole numbers
    try {
    number1 = Double.parseDouble(
    this.diameterBox.getText());
    number2 = Double.parseDouble(
    this.lengthBox.getText());
    number3 = Double.parseDouble(
    this.heightBox.getText());
    number4 = Double.parseDouble(
    this.widthBox.getText());
    }

    catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Must be a whole number",
    "Error", JOptionPane.ERROR_MESSAGE);
    return;
    }
    //My attempt at formatting the decimals (not working so well):
    //DecimalFormat currencyFormat = new DecimalFormat("#, ###.##");

    //Rectangle portion (not-working):

    if(materialDropDown.getSelectedIndex()==0)
    totalPrice.setText("The price is: $"
    + ((0.098*(number2*number3*number4)*3.06)));

    else if(materialDropDown.getSelectedIndex()==1)
    totalPrice.setText("The price is: $"
    + ((0.1*number2*number3*number4)*5.61));

    //Cylinder portion (working fine):
    if(materialDropDown.getSelectedIndex()==0)
    totalPrice.setText("The price is: $"
    + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06));
    else if(materialDropDown.getSelectedIndex()==1)
    totalPrice.setText("The price is: $"
    + ((0.1*(((number1/2)*(number1/2))*3.14159*number2))*5.61));

    Curiously, there are no errors that pop up. Basically, there are two JLabels coded to show the weight and price of the goods. The outputs are as follows:

    When Rectangle is selected (regardless of the input numbers, integer or decimal):
    Weight (lb): 0.0
    The price is: $0.0

    When Cylinder is selected (based on random test values in integer and decimal format):
    Weight (lb): 4.65...
    The price is: $14.29496...

    Here's a picture, if you can make it out:
    demo.jpg

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE GOES HERE
    [/code]
    to get highlighting and preserve formatting.

    It should look like this:
      int x = 1;
      x = y+2;


    Please Don't post images. Copy the output and paste it here. Add some debugging println() statements if needed.

    Also please explain what is wrong with the current output and show what it should be.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    double number1, number2, number3, number4;
            // Make sure numbers entered are whole numbers
          try {
            number1 = Double.parseDouble(
                   this.diameterBox.getText());
            number2 = Double.parseDouble(
                   this.lengthBox.getText());
            number3 = Double.parseDouble(
                   this.heightBox.getText());
            number4 = Double.parseDouble(
                    this.widthBox.getText());
        }                                               
          catch (Exception e) {
              JOptionPane.showMessageDialog(this, "Must be a whole number", 
                      "Error", JOptionPane.ERROR_MESSAGE);
              return;
          } 
             //DecimalFormat currencyFormat = new DecimalFormat("#, ###.##");
             //double number1 = currencyFormat.format(num1);
     
          //If 'Rectangle' is selected: (not working)
          if(shapeDropDown.getSelectedIndex()==1) 
          //6061
          if(materialDropDown.getSelectedIndex()==0) 
          totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
          //2024
          else if(materialDropDown.getSelectedIndex()==1)  
          totalPrice.setText("The price is: $"
                  + ((0.1*number2*number3*number4)*5.61));
     
    //Working, cylindrical portion:
          if(shapeDropDown.getSelectedIndex()==2);
          //6063 
          if(materialDropDown.getSelectedIndex()==0) 
          totalPrice.setText("The price is: $"
                  + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06));
          //2024
          else if(materialDropDown.getSelectedIndex()==1) 
          totalPrice.setText("The price is: $"
                  + ((0.1*(((number1/2)*(number1/2))*3.14159*number2))*5.61));

    Ah, thank you.

    If there was an output that I could copy, I would. The outputs are contained within JLabel text, the coding for it is right there. At least the price portion is. The weight and price appear to have the same problem, however. And thank you for your patience!

    Sorry I keep editing this. So a proper output shows up more or less as I showed earlier:
    Weight (lb): 4.65...
    The price is: $14.29496...

    What's actually showing up instead:
    Weight (lb): 0.0
    The price is: $0.0

    When the cylinder portion was malfunctioning like that, it was just a matter of changing the variables from int to double. But that caused the rectangle portion to malfunction instead.
    Last edited by Cal S.; September 9th, 2014 at 05:32 PM. Reason: mistake in formatting

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    Add some debug code next to all the setText() calls that prints the values so they can be copied. For example:
      String  msg = "The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06));
      totalPrice.setText(msg);
      System.out.println(msg);

    BTW the formatting needs work. The {}s are missing and the statements inside of the if should be indented.

    You're still missing this:
    Also please explain what is wrong with the current output and show what it should be.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Thank you!

    It seems to work this way now. This:

    if(materialDropDown.getSelectedIndex()==0) 
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
                 String  msg = "The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06));
                 totalPrice.setText(msg);
                 System.out.println(msg);

    Outputs the answer just fine!
    run:
    The price is: $8.20563521300000004

    Still too many decimals, but now that I see it can be converted to a string, I think I've run across a way to fix that. I'll troubleshoot a bit more to see if I can condense that to take up less room, but you've given me a big leg up, I surely do appreciate it!

    The reason the formatting was off and there weren't any curly brackets was because the code is over 700 lines long, I had to abbreviate it. Thanks again!

    If I may ask one more question, for future reference, was it the conversion back to a string that did it?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    too many decimals,
    See the DecimalFormat class for how to control the number of digits shown.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Quote Originally Posted by Norm View Post
    See the DecimalFormat class for how to control the number of digits shown.
    Yes indeed, that's what I was thinking. Thanks again!

  14. #14
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Looks like celebration was a tad premature on my account.

    I'm not entirely sure how that made the first one work, but it's not working on the second or subsequent lines of code. They're still displaying a $0.0 answer regardless. This is what I've tried:

    //If 'Rectangle' is selected: 
          if(shapeDropDown.getSelectedIndex()==1) 
          //6061 (WORKS)
          if(materialDropDown.getSelectedIndex()==0) 
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
                 String  msg = "The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06));
                 totalPrice.setText(msg);
          //2024 (DOESN'T WORK)
         else if(materialDropDown.getSelectedIndex()==1) 
              totalPrice.setText("The price is: $"
                  + ((0.1*number2*number3*number4)*5.61));
                  String  msg2 = "The price is: $"
                  + ((0.1*(number2*number3*number4)*5.61));
                 totalPrice.setText(msg2);
     
    //Later on, separated by hundreds of lines of code, this works beautifully...
     
    //Cylinder code
    if(shapeDropDown.getSelectedIndex()==2);
          //6063 (WORKS)
          if(materialDropDown.getSelectedIndex()==0) 
              totalPrice.setText("The price is: $"
                  + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06));
          //2024 (WORKS) 
          else if(materialDropDown.getSelectedIndex()==1) 
              totalPrice.setText("The price is: $"
                  + ((0.1*(((number1/2)*(number1/2))*3.14159*number2))*5.61));
    the first 'if' statement functions, but the 'else if' statements no longer function for the rectangular portion. Also, an error appears that says 'else' without 'if', which did not appear before. When I changed that to just an 'if' statement, it displayed the $0.0 output.

    Curiously, the 'String msg' statement, while it contains all the same calculations and variables as the original statement, will not function without the original statement. It feels strangely redundant...

    Just looking at the edited versus old coding, it does not appear that much has changed except how the message is written to the JLabel as a string instead of an output. Why does that make a difference? Nothing else changed, so it does not appear that the mathematics or variables are poorly coded. Is there an alternate way to get it working?

    EDIT: Ok, so the 'else' without 'if' was poor formatting on my part and is fixed now. Still didn't make the code work properly.
    Last edited by Cal S.; September 10th, 2014 at 10:44 AM.

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    The first thing I see about the code is the missing {}s. Always put code after if statements(and while etc) inside of {}s
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Strangely the cylinder portion functions properly without them. Good fortune on my part, I suspect. Still doesn't fix the errors encountered with the rectangle portion, as amended here:

    //If 'Rectangle' is selected:
          if(shapeDropDown.getSelectedIndex()==1) {
          //6061 (doesn't work with {} now)
          if(materialDropDown.getSelectedIndex()==0) {
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
                 String  msg = "The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06));
                 totalPrice.setText(msg);
          //2024 (Still doesn't work)
          }else if(materialDropDown.getSelectedIndex()==1) {
              totalPrice.setText("The price is: $"
                  + ((0.1*number2*number3*number4)*5.61));
                  String  msg2 = "The price is: $"
                  + ((0.1*(number2*number3*number4)*5.61));
                 totalPrice.setText(msg2);

    In fact, adding the {} has caused the previously working first expression to display the same malfunctioning $0.0 output it used to. I'm very confused now.

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    The ending }s are missing. The formatting still needs work:
          if(shapeDropDown.getSelectedIndex()==1) {
    	      //6061 (doesn't work with {} now)
    	      if(materialDropDown.getSelectedIndex()==0) {
    	          totalPrice.setText("The price is: $"			  //<<<<< First time
    	              + ((0.098*(number2*number3*number4)*3.06)));
    	          String  msg = "The price is: $"
    	              + ((0.098*(number2*number3*number4)*3.06));
    	          totalPrice.setText(msg);	   //???? Why two times
    	      //2024 (Still doesn't work)
    	      }else if(materialDropDown.getSelectedIndex()==1) {
    	          totalPrice.setText("The price is: $"
    	              + ((0.1*number2*number3*number4)*5.61));
    	          String  msg2 = "The price is: $"
    	              + ((0.1*(number2*number3*number4)*5.61));
    	          totalPrice.setText(msg2);			
                 }
    	 }

    Why are there two calls to setText()?

    Does the debug printout show the problem? Post it and add some comments saying what is wrong with it.

    The println(msg) statements are missing.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Let me try to go through the brief history with comments in the code:

    Real quick, this code is hundreds of lines long. The ending }s are in fact in the code, but not for another 50 lines or so. This is just a quick snippet.

    //If 'Rectangle' is selected:
          if(shapeDropDown.getSelectedIndex()==1) {
          //6061
          if(materialDropDown.getSelectedIndex()==0) {      //Before {} added, these lines functioned with the 2nd setText added, but subsequent 'else if' statements didn't.
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
                 String  msg = "The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06));
                 totalPrice.setText(msg);                     // Would not display any answer at all without both declarations of setText. 
     
                      }

    As contrasted with this fully functional code, that by rights shouldn't be:

    //If 'Cylinder' is selected:
     
          if(shapeDropDown.getSelectedIndex()==2);   //0 usage of {}, and yet all the math and inputs work wonderfully. 
          //6063 
          if(materialDropDown.getSelectedIndex()==0) 
              totalPrice.setText("The price is: $"
                  + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06));
          //2024
          else if(materialDropDown.getSelectedIndex()==1) 
              totalPrice.setText("The price is: $"
                  + ((0.1*(((number1/2)*(number1/2))*3.14159*number2))*5.61));

    I don't understand how this is possible...

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    Where are the println statements to show what the results are?
    They would create some examples that could be posted to show the problems.

    If the adding of {}s changes how the code executes then that is a problem that needs to be fixed.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    I'm sorry, but the "Println" statements would literally only show what's written to the JLabel in the setText statements; the '$0.0' outputs. There are no errors, it just fails to do the math properly. Somehow it works only when it looks like this:
    if(materialDropDown.getSelectedIndex()==0) 
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
                 String  msg = "The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06));
                 totalPrice.setText(msg);
                   //But then subsequent statements don't work, and it has to look exactly like this with both setText statements

    Just added the {} to the Cylinder portion. Nothing changed. It still works fine while the rectangle portion doesn't. There has to be a problem with the way the mathematics are being handled within the rectangular portion that isn't a problem in the cylinder portion.

    //By way of reminder, these are the variables I'm using:
     
    double number1, number2, number3, number4;
            // Make sure numbers entered are whole numbers
          try {
            number1 = Double.parseDouble(
                   this.diameterBox.getText());
            number2 = Double.parseDouble(
                   this.lengthBox.getText());
            number3 = Double.parseDouble(
                   this.heightBox.getText());
            number4 = Double.parseDouble(
                    this.widthBox.getText());
        }                                               
          catch (Exception e) {
              JOptionPane.showMessageDialog(this, "Must be a whole number", 
                      "Error", JOptionPane.ERROR_MESSAGE);
              return;
          } 
     
    //And then the math that doesn't work: 
    if(materialDropDown.getSelectedIndex()==0) {
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06))); //and so on
    //Versus the math that does work:
    if(materialDropDown.getSelectedIndex()==0) {
              totalPrice.setText("The price is: $"
                  + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06)); // and so on

    Am I missing () somewhere? Should I be combining the 'number#' variables in other declarations? What is it about the cylinder math that works when the simpler geometric formulas of the rectangular math fails and returns a '$0.0' output?

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    Somehow it works only when it looks like this:
    If that code is properly formatted it would be like this:
    if(materialDropDown.getSelectedIndex()==0) 
              totalPrice.setText("The price is: $"
                  + ((0.098*(number2*number3*number4)*3.06)));
     
     // Following 2 statement are not in the if
     String  msg = "The price is: $"
               + ((0.098*(number2*number3*number4)*3.06));
     totalPrice.setText(msg);
    Indentations do not change the enclosing. {}s do change what is enclosed.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #22
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Norm, I just want to say I really appreciate your help thus far. I also thank you for your patience in dealing with me. Here is the code in its (relative) entirety. I have determined that if I comment out the cylinder portion then the rectangle portion works. Should have tried that sooner in hindsight. Probably has something to do with the long 'if' 'else if' statements. Is the cylinder overriding the rectangular section? I don't know if showing you the whole thing will help, but here she is:

            double number1, number2, number3, number4;
            // Make sure numbers entered are whole numbers
          try {
            number1 = Double.parseDouble(
                   this.diameterBox.getText());
            number2 = Double.parseDouble(
                   this.lengthBox.getText());
            number3 = Double.parseDouble(
                   this.heightBox.getText());
            number4 = Double.parseDouble(
                    this.widthBox.getText());
        }                                               
          catch (Exception e) {
              JOptionPane.showMessageDialog(this, "Must be a whole number", 
                      "Error", JOptionPane.ERROR_MESSAGE);
              return;
          } 
             //DecimalFormat currencyFormat = new DecimalFormat("#, ###.##");
             //double number1 = currencyFormat.format(num1);
     
          //If 'Rectangle' is selected:
          if(shapeDropDown.getSelectedIndex()==1) {
          //6061
          if(materialDropDown.getSelectedIndex()==0) {
              totalPrice.setText("The price is: $"
                 + ((0.098*(number2*number3*number4)*3.06)));
           //2024
          } else if(materialDropDown.getSelectedIndex()==1) {
              totalPrice.setText("The price is: $"
                  + ((0.1*number2*number3*number4)*5.61));
          //7075
          }  else if(materialDropDown.getSelectedIndex()==2) {
              totalPrice.setText("The price is: $"
                  + ((0.101*number2*number3*number4)*7.85));
          //Mic-6
          } else if(materialDropDown.getSelectedIndex()==3) {
              totalPrice.setText("The price is: $"
                  + ((0.097544*number2*number3*number4)*2.28));
          //6063
          }else if(materialDropDown.getSelectedIndex()==4) {
              totalPrice.setText("The price is: $"
                  + ((0.0975*number2*number3*number4)*4.48));
          //303
          }  else if(materialDropDown.getSelectedIndex()==5) {
              totalPrice.setText("The price is: $"
                  + ((0.2899*number2*number3*number4)*5.48));
          //304
          } else if(materialDropDown.getSelectedIndex()==6) {
              totalPrice.setText("The price is: $"
                  + ((0.28902*number2*number3*number4)*4.84));
          //316
          } else if(materialDropDown.getSelectedIndex()==7) {
              totalPrice.setText("The price is: $"
                  + ((0.284*number2*number3*number4)*5.55));
          //316L
          }  else if(materialDropDown.getSelectedIndex()==8) {
              totalPrice.setText("The price is: $"
                  + ((0.28902*number2*number3*number4)*5.55));
          //17-4
          } else if(materialDropDown.getSelectedIndex()==9) {
              totalPrice.setText("The price is: $"
                  + ((0.282*number2*number3*number4)*5.33));
          //1018
          } else if(materialDropDown.getSelectedIndex()==10) {
              totalPrice.setText("The price is: $"
                  + ((0.2843*number2*number3*number4)*1.37));
          //4140
          } else if(materialDropDown.getSelectedIndex()==11) {
              totalPrice.setText("The price is: $"
                  + ((0.282*number2*number3*number4)*2.6));
          //OI
          } else if(materialDropDown.getSelectedIndex()==12) {
              totalPrice.setText("The price is: $"
                  + ((0.282*number2*number3*number4)*815.84));
          //Grade 2
          } else if(materialDropDown.getSelectedIndex()==13) {
              totalPrice.setText("The price is: $"
                  + ((0.163*number2*number3*number4)*39.91));
          //B360
          } else if(materialDropDown.getSelectedIndex()==14) {
              totalPrice.setText("The price is: $"
                  + ((0.307*number2*number3*number4)*4.92));
          //Acetal
          } else if(materialDropDown.getSelectedIndex()==15) {
              totalPrice.setText("The price is: $"
                  + ((0.0564*number2*number3*number4)));
          //CPVC
          } else if(materialDropDown.getSelectedIndex()==16) {
              totalPrice.setText("The price is: $"
                  + (0.05635*number2*number3*number4)*0.23);
          //PVC
          } else if(materialDropDown.getSelectedIndex()==17) {
              totalPrice.setText("The price is: $"
                  + (0.051*number2*number3*number4));
          //UHMW
          } else if(materialDropDown.getSelectedIndex()==18) {
              totalPrice.setText("The price is: $"
                  + (0.0336*number2*number3*number4));     
          }
     
     
          //If 'Cylinder' is selected:
     
        } else if(shapeDropDown.getSelectedIndex()==2); {
          //6063 
          if(materialDropDown.getSelectedIndex()==0) {
              totalPrice.setText("The price is: $"
                  + ((0.098*(((number1/2)*(number1/2))*3.14159*number2))*3.06));
           //2024
          } else if(materialDropDown.getSelectedIndex()==1) {
              totalPrice.setText("The price is: $"
                  + ((0.1*(((number1/2)*(number1/2))*3.14159*number2))*5.61));
          //7075
          } else if(materialDropDown.getSelectedIndex()==2) {
              totalPrice.setText("The price is: $"
                  + ((0.101*(((number1/2)*(number1/2))*3.14159*number2))*7.85));
          //Mic-6
          } else if(materialDropDown.getSelectedIndex()==3) {
              totalPrice.setText("The price is: $"
                  + ((0.097544*(((number1/2)*(number1/2))*3.14159*number2))*2.28));
          //6063
          } else if(materialDropDown.getSelectedIndex()==4) {
              totalPrice.setText("The price is: $"
                  + ((0.0975*(((number1/2)*(number1/2))*3.14159*number2))*4.48));
          //303
          } else if(materialDropDown.getSelectedIndex()==5) {
              totalPrice.setText("The price is: $"
                  + ((0.2899*(((number1/2)*(number1/2))*3.14159*number2))*5.48));
          //304
          } else if(materialDropDown.getSelectedIndex()==6) {
              totalPrice.setText("The price is: $"
                  + ((0.28902*(((number1/2)*(number1/2))*3.14159*number2))*4.84));
          //316
          } else if(materialDropDown.getSelectedIndex()==7){
              totalPrice.setText("The price is: $"
                  + ((0.284*(((number1/2)*(number1/2))*3.14159*number2))*5.55));
          //316L
          } else if(materialDropDown.getSelectedIndex()==8) {
              totalPrice.setText("The price is: $"
                  + ((0.28902*(((number1/2)*(number1/2))*3.14159*number2))*5.55));
          //17-4
          } else if(materialDropDown.getSelectedIndex()==9) {
              totalPrice.setText("The price is: $"
                  + ((0.282*(((number1/2)*(number1/2))*3.14159*number2))*5.33));
          //1018
          } else if(materialDropDown.getSelectedIndex()==10) {
              totalPrice.setText("The price is: $"
                  + ((0.2843*(((number1/2)*(number1/2))*3.14159*number2))*1.37));
          //4140
          } else if(materialDropDown.getSelectedIndex()==11) {
              totalPrice.setText("The price is: $"
                  + ((0.282*(((number1/2)*(number1/2))*3.14159*number2))*2.60));
          //OI
          } else if(materialDropDown.getSelectedIndex()==12) {
              totalPrice.setText("The price is: $"
                  + ((0.282*(((number1/2)*(number1/2))*3.14159*number2))*815.84));
          //Grade 2
          } else if(materialDropDown.getSelectedIndex()==13) {
              totalPrice.setText("The price is: $"
                  + ((0.163*(((number1/2)*(number1/2))*3.14159*number2))*39.91));
          //B360
          } else if(materialDropDown.getSelectedIndex()==14) {
              totalPrice.setText("The price is: $"
                  + ((0.307*(((number1/2)*(number1/2))*3.14159*number2))*4.92));
          //Acetal
          } else if(materialDropDown.getSelectedIndex()==15) {
              totalPrice.setText("The price is: $"
                  + (0.0564*(((number1/2)*(number1/2))*3.14159*number2)));
          //CPVC
          } else if(materialDropDown.getSelectedIndex()==16) {
              totalPrice.setText("The price is: $"
                  + ((0.05635*(((number1/2)*(number1/2))*3.14159*number2))*0.23));
          //PVC
          } else if(materialDropDown.getSelectedIndex()==17){
              totalPrice.setText("The price is: $"
                  + (0.0564*(((number1/2)*(number1/2))*3.14159*number2)));
          //UHMW
          } else if(materialDropDown.getSelectedIndex()==18){
              totalPrice.setText("The price is: $"
                  + (0.0564*(((number1/2)*(number1/2))*3.14159*number2)));
          }}

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    The code needs some println statements to show you what is happening. There are many calls to the setText() method, which one(s) are putting bad data into the totalPrice field?
    If there were a println next to each setText() you'd soon see which one is putting the bad values into totalPrice.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #24
    Junior Member
    Join Date
    Sep 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Formatting answers to 2 decimal places

    Because it's a GUI, the output shows up in the JLabel that has its setText determined in each statement without the need for the println statements. I can and have run line-by-line debug through that.

    I wouldn't say it's bad data, it's just no data. The code executes when a 'calculate' button is clicked. As I've been debugging it, when I have the cylinder section commented out, then at least the rectangle section does work. When I have both visible, then only the cylinder section works. Therefore, it's probably something mixed up in my method of writing the 'if' and 'else if' statements between the two main sections; thus causing the GUI to only execute the last code it finds within the 'calculate' button's code.

    So the math works for both sections, but it appears that it's simply not reading the rectangle section when it executes the code.

    Would it work completely if I had the 'Rectangle' and 'Cylinder' in JcheckBoxes instead? Or perhaps I should try a different method for the rectangle and cylinder, with 'if' 'else if' statements embedded in the main sections?

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Formatting answers to 2 decimal places

    it's simply not reading the rectangle section when it executes the code.
    Why not? What controls the execution of that section of code? What are the values of the variables when that area of the code is executed?
    If you are interactively debugging the code you should be able to see the values of the variables that control the code's execution.

    my method of writing the 'if' and 'else if' statements
    That is likely. From the code you've posted there have been a sloppy usage of {}s making the code hard to read and understand.
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. How do I get my answers to out with 2 decimal places?
    By dunnage888 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 8th, 2012, 12:23 PM
  2. New to Java Need 2 decimal places, please :). Here is my code
    By Charyl in forum Member Introductions
    Replies: 2
    Last Post: June 28th, 2011, 03:06 AM
  3. Java program to format a double value to 2 decimal places
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 3
    Last Post: December 4th, 2010, 04:08 PM
  4. float to 2 decimal places
    By fh84 in forum Java Theory & Questions
    Replies: 3
    Last Post: November 25th, 2009, 11:27 AM
  5. [SOLVED] How to use decimal place when formatting an output?
    By napenthia in forum Java Theory & Questions
    Replies: 2
    Last Post: April 27th, 2009, 03:17 AM