Results 1 to 17 of 17
  1. #1
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Rounding to n decimal place.

    Hey I was wondering if there was a method anywhere which allows me to round to a specified decimal point?

    I was hoping i could put a variable into the parameter which will change throughout the program.

    I am making a calculator program.

    Thanks.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,037
    Rep Power
    10

    Default Re: Rounding to n decimal place.

    Doing a google search of "java rounding" comes up with a ton of results. Were you having trouble with a particular approach?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Rounding to n decimal place.

    Also, you may wish to clarify your question: are you talking about rounding a number or rounding the String representation of a number? Often folks mention the first but really mean the second.

  4. #4
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Re: Rounding to n decimal place.

    I did google that. Because i need to put a variable in for the current value which should be displayed on my calculator and how many decimal points i want it to be rounded to. I was wondering if there was any method which took these two parameters? Which I couldn't find on google. Is there any method for this?

    I tried Math.round but that didn't let me round to any decimal points.

    I am rounding a number.

    Thanks

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Rounding to n decimal place.

    Quote Originally Posted by HarleyRowland View Post
    I did google that. Because i need to put a variable in for the current value which should be displayed on my calculator and how many decimal points i want it to be rounded to. I was wondering if there was any method which took these two parameters? Which I couldn't find on google. Is there any method for this?
    It's as I suspected. You should not look towards rounding the number but rather the String display of the number. Look at using a DecimalFormatter object or the String.format(...) method. You can find much about both of these guys via Google, but if you're still stuck, please post your attempt here and let's work with you on this.

    I tried Math.round but that didn't let me round to any decimal points.
    This tries to round the number itself which is not what you need.

    I am rounding a number.
    No, you're not actually.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Rounding to n decimal place.

    For example:

    Java Code:
    import java.text.DecimalFormat;
    
    public class NumberFormatEg {
       public static void main(String[] args) {
          double foo = 1.0/3.0;
          
          System.out.println("foo: " + foo);
          
          DecimalFormat decimalFormat = new DecimalFormat("0.###");
          
          System.out.println("foo formatted: " + decimalFormat.format(foo));
       }
    }
    This prints out:

    foo: 0.3333333333333333
    foo formatted: 0.333

  7. #7
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Re: Rounding to n decimal place.

    Hello, i tried it and it kind of worked. Am i allowed to put a variable into the parameters of the DecimalFormat creation? As long as it is the right string format? As i have a loop which adds a "#" to a variable which is originally "#." every time i need the rounding to a decimal point to go up by one.

  8. #8
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,037
    Rep Power
    10

    Default Re: Rounding to n decimal place.

    Quote Originally Posted by HarleyRowland View Post
    Hello, i tried it and it kind of worked. Am i allowed to put a variable into the parameters of the DecimalFormat creation? As long as it is the right string format? As i have a loop which adds a "#" to a variable which is originally "#." every time i need the rounding to a decimal point to go up by one.
    What happened when you tried?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Re: Rounding to n decimal place.

    i get this error:

    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Rounding to n decimal place.

    You will probably want to post demo code to show what you're actually trying to do, along with the actual error message. The best code to post is a small self-contained program that we can try to run that demonstrates for us the error, similar to the small program that I posted above.

  11. #11
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Re: Rounding to n decimal place.

    Java Code:
    public class Calculator
    {
        private boolean decimal;
        private double currentValue;
        private double previousValue;
        private double timesNumber;
        private double functionValue;
        private int timesNumberCondition1;
        private int timesNumberCondition2;
        private int DFTextCondition1;
        private int DFTextCondition2;
        private DecimalFormat decimalFormat;
        private String DFText;
        public Calculator(){
            decimal = false;
            currentValue = 0.0;
            previousValue = 0.0;
            timesNumber = 1.0;
            functionValue = 0.0;
            timesNumberCondition1 = 0;
            timesNumberCondition2 = 1;
            DFTextCondition1 = 0;
            DFTextCondition2 = -1;
            decimalFormat = new DecimalFormat("DFText");
            DFText = "#.#";
        }
    
        public void afterFunction()
        {
            decimal = false;
            timesNumberCondition1 = 0;
            timesNumber = 1.0;
            timesNumberCondition2 = 1;
            DFText = "#.#";
            DFTextCondition1 = 0;
            DFTextCondition2 = -1;
        }
      
        public void dot() {
            decimal = true;
        }
     
    //this method is used to add the correct amount of "#"s for the current number, i have got that to work.
        public void number(int n) { 
            if(decimal == false) {
                currentValue = currentValue * 10 + n;
            } else {
               while(timesNumberCondition1 < timesNumberCondition2){
                   timesNumber = timesNumber * 10;
                   timesNumberCondition1++;
                   if(timesNumberCondition1 > 1){
                    while(DFTextCondition1 <= DFTextCondition2){
                        DFText = DFText + "#";
                        System.out.println(DFText);
                        DFTextCondition1++;
                    }
                }
               
                }
               previousValue = currentValue;
               currentValue = n / timesNumber;
               currentValue = currentValue + previousValue;
               timesNumberCondition2++;
               DFTextCondition2++;
            }
        }
    
    //when this is returned i get the error message  
        public String currentDisplay() { 
          String text = Double.toString(currentValue); 
            text = decimalFormat.format(text);
            return text;
        }
    }
    this is the error i get:

    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number
    at java.text.DecimalFormat.format(DecimalFormat.java: 505)
    at java.text.Format.format(Format.java:157)
    at Calculator.currentDisplay(Calculator.java:203)
    at CalculatorGUI.actionPerformed(CalculatorGUI.java:1 77)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.jav a:6505)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3321)
    at java.awt.Component.processEvent(Component.java:627 0)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719 )
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:703)
    at java.awt.EventQueue.access$000(EventQueue.java:102 )
    at java.awt.EventQueue$3.run(EventQueue.java:662)
    at java.awt.EventQueue$3.run(EventQueue.java:660)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:676)
    at java.awt.EventQueue$4.run(EventQueue.java:674)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 673)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:97)

    calculatorGUI is just a class which calls the methods.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,763
    Blog Entries
    7
    Rep Power
    21

    Default Re: Rounding to n decimal place.

    Quote Originally Posted by HarleyRowland View Post
    Java Code:
            decimalFormat = new DecimalFormat("DFText");
    You can't construct a DecimalFormat object like that; read its API documentation.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Re: Rounding to n decimal place.

    I changed it to:

    Java Code:
    DFText = "#.#";
    decimalFormat = new DecimalFormat(DFText);
    but i still get the same error. I really don't know what i'm doing wrong.

    Thanks.
    Last edited by HarleyRowland; 03-02-2013 at 04:36 PM.

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,763
    Blog Entries
    7
    Rep Power
    21

    Default Re: Rounding to n decimal place.

    Your method in line #69 tries to format a String; it can't do that, it can only format an object of type Number (or a subclass thereof); autoboxing takes care that you can format a primitive double.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  15. #15
    HarleyRowland is offline Member
    Join Date
    Feb 2013
    Posts
    26
    Rep Power
    0

    Default Re: Rounding to n decimal place.

    Wow thankyou! it works now spent ages trying to work that out. Is it okay to delete my code in post above?

  16. #16
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: Rounding to n decimal place.

    Quote Originally Posted by HarleyRowland View Post
    Is it okay to delete my code in post above?
    No!

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,763
    Blog Entries
    7
    Rep Power
    21

    Default Re: Rounding to n decimal place.

    Quote Originally Posted by HarleyRowland View Post
    Wow thankyou! it works now spent ages trying to work that out. Is it okay to delete my code in post above?
    To elaborate a bit: if you'd remove your code you'd rip the thread apart and it won't make much sense anymore to other readers who might've hit this page through google etc. Better leave all your replies as they are.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Rounding to one decimal place
    By threlot in forum New To Java
    Replies: 9
    Last Post: 10-16-2012, 06:52 AM
  2. Rounding Decimal Places
    By neverbend in forum JCreator
    Replies: 4
    Last Post: 09-30-2011, 12:41 AM
  3. Rounding decimal error
    By NixasMuraki in forum New To Java
    Replies: 3
    Last Post: 06-01-2011, 02:07 AM
  4. Compile Error (decimal rounding attempt)
    By mylosol in forum New To Java
    Replies: 2
    Last Post: 05-09-2011, 12:13 AM
  5. rounding double to two decimal places
    By javaMike in forum Advanced Java
    Replies: 15
    Last Post: 03-10-2010, 01:04 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •