# Rounding to n decimal place.

• 02-26-2013, 06:21 PM
HarleyRowland
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.
• 02-26-2013, 06:23 PM
KevinWorkman
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?
• 02-26-2013, 06:34 PM
Fubarable
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.
• 02-26-2013, 06:43 PM
HarleyRowland
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
• 02-26-2013, 07:11 PM
Fubarable
Re: Rounding to n decimal place.
Quote:

Originally Posted by HarleyRowland
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.

Quote:

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.

Quote:

I am rounding a number.
No, you're not actually.
• 02-26-2013, 07:16 PM
Fubarable
Re: Rounding to n decimal place.
For example:

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
• 02-27-2013, 10:54 PM
HarleyRowland
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.
• 02-28-2013, 04:00 PM
KevinWorkman
Re: Rounding to n decimal place.
Quote:

Originally Posted by HarleyRowland
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?
• 03-02-2013, 03:06 PM
HarleyRowland
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
• 03-02-2013, 03:51 PM
Fubarable
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.
• 03-02-2013, 04:10 PM
HarleyRowland
Re: Rounding to n decimal place.
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)

calculatorGUI is just a class which calls the methods.
• 03-02-2013, 04:20 PM
JosAH
Re: Rounding to n decimal place.
Quote:

Originally Posted by HarleyRowland
Code:

`        decimalFormat = new DecimalFormat("DFText");`

You can't construct a DecimalFormat object like that; read its API documentation.

kind regards,

Jos
• 03-02-2013, 04:33 PM
HarleyRowland
Re: Rounding to n decimal place.
I changed it to:

Code:

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

Thanks.
• 03-02-2013, 05:10 PM
JosAH
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
• 03-02-2013, 07:25 PM
HarleyRowland
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?
• 03-02-2013, 09:48 PM
DarrylBurke
Re: Rounding to n decimal place.
Quote:

Originally Posted by HarleyRowland
Is it okay to delete my code in post above?

No!

db
• 03-03-2013, 07:34 AM
JosAH
Re: Rounding to n decimal place.
Quote:

Originally Posted by HarleyRowland
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