Java Forum / General / March 2007
How to Round a float to an nearest whole number
Don - 03 Mar 2007 01:27 GMT I need to round a float to the nearest whole number using DecimalFormat (specific requirements for a program). I have tried DecimalFormat grade = new DecimalFormat("0"); but it does nothing at all. What should I put in the parentheses to just round to the nearest whole number?
Knute Johnson - 03 Mar 2007 01:42 GMT > I need to round a float to the nearest whole number using > DecimalFormat (specific requirements for a program). I have tried > DecimalFormat grade = new DecimalFormat("0"); > but it does nothing at all. What should I put in the parentheses to > just round to the nearest whole number? It works just fine for me.
import java.text.*;
class test3 { public static void main(String[] args) { float value = 1.9f; DecimalFormat grade = new DecimalFormat("0"); System.out.println(grade.format(value)); } }
C:\>java test3 2
 Signature Knute Johnson email s/nospam/knute/
Don - 03 Mar 2007 01:59 GMT On Mar 2, 8:42 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com> wrote:
> > I need to round a float to the nearest whole number using > > DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 22 lines] > Knute Johnson > email s/nospam/knute/ What does the "f" for?
Joshua Cranmer - 03 Mar 2007 02:01 GMT > On Mar 2, 8:42 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com> > wrote: [quoted text clipped - 25 lines] > > What does the "f" for? The 'f' makes it a float literal and not a double (which a floating point is by default).
Don - 03 Mar 2007 02:17 GMT > > On Mar 2, 8:42 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com> > > wrote: [quoted text clipped - 30 lines] > > - Show quoted text - So would I need to use "f" when formatting a variable? If so, how would I do that?
Patricia Shanahan - 03 Mar 2007 02:27 GMT >>> On Mar 2, 8:42 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com> >>> wrote: [quoted text clipped - 12 lines] >>>> } >>>> } ...
> So would I need to use "f" when formatting a variable? If so, how > would I do that? You need the "f", or a (float) cast, to initialize a float variable with a literal. It has absolutely nothing to do with the formatting, which works just the same for double:
import java.text.*;
class test3 { public static void main(String[] args) { double value = 1.9; DecimalFormat grade = new DecimalFormat("0"); System.out.println(grade.format(value)); } }
Patricia
Arne Vajhøj - 03 Mar 2007 02:38 GMT > On Mar 2, 8:42 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com> > wrote: >> float value = 1.9f;
> What does the "f" for? float (as in "not double").
Arne
jupiter - 03 Mar 2007 03:32 GMT >> On Mar 2, 8:42 pm, Knute Johnson >> <nos...@rabbitbrush.frazmtn.com> [quoted text clipped - 6 lines] > > Arne But I ordered a double float with vanilla.
Don - 03 Mar 2007 03:13 GMT > I need to round a float to the nearest whole number using > DecimalFormat (specific requirements for a program). I have tried > DecimalFormat grade = new DecimalFormat("0"); > but it does nothing at all. What should I put in the parentheses to > just round to the nearest whole number? OK, I'll show my code I guess... Try compiling
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; import java.text.DecimalFormat;
public class Ch7Ex4 extends JFrame implements ActionListener { JTextPane textPane = new JTextPane();
int[] grades = new int[0]; float average,gTotal,Average;
public Ch7Ex4() { super("Grade Averager"); } public JMenuBar createMenuBar() { //create an instance of the menu JMenuBar mnuBar = new JMenuBar(); setJMenuBar(mnuBar);
//construct and populate the File menu JMenu mnuFile = new JMenu("File", true); mnuFile.setMnemonic(KeyEvent.VK_F); mnuFile.setDisplayedMnemonicIndex(0); mnuBar.add(mnuFile);
JMenuItem mnuFileExit = new JMenuItem("Exit"); mnuFileExit.setMnemonic(KeyEvent.VK_X); mnuFileExit.setDisplayedMnemonicIndex(1); mnuFile.add(mnuFileExit); mnuFileExit.setActionCommand("Exit"); mnuFileExit.addActionListener(this);
//construct and populate the Edit menu JMenu mnuEdit = new JMenu("Edit", true); mnuEdit.setMnemonic(KeyEvent.VK_E); mnuFileExit.setDisplayedMnemonicIndex(0); mnuBar.add(mnuEdit);
JMenuItem mnuEditInsert = new JMenuItem("Insert New Grades"); mnuEditInsert.setMnemonic(KeyEvent.VK_I); mnuEditInsert.setDisplayedMnemonicIndex(0); mnuEdit.add(mnuEditInsert); mnuEditInsert.setActionCommand("Insert"); mnuEditInsert.addActionListener(this);
return mnuBar; }
//create the content pane public Container createContentPane() { //create the JTextPane and center panel JPanel centerPanel = new JPanel(); setTabsAndStyles(textPane); textPane = addTextToTextPane(); JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setPreferredSize(new Dimension(650, 200)); centerPanel.add(scrollPane);
//create Container and set attributes Container c = getContentPane(); c.setLayout(new BorderLayout(10,10)); c.add(centerPanel, BorderLayout.CENTER);
return c; }
//method to create tab stops and set font styles protected void setTabsAndStyles(JTextPane textPane) { //create Tab Stops TabStop[] tabs = new TabStop[3]; tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE); tabs[1] = new TabStop(295, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE); tabs[2] = new TabStop(450, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE); TabSet tabset = new TabSet(tabs);
//set Tab Style StyleContext tabStyle = StyleContext.getDefaultStyleContext(); AttributeSet aset = tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset); textPane.setParagraphAttributes(aset, false);
//set Font Style Style fontStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = textPane.addStyle("regular", fontStyle); StyleConstants.setFontFamily(fontStyle, "SansSerif");
Style s = textPane.addStyle("italic", regular); StyleConstants.setItalic(s, true);
s = textPane.addStyle("bold", regular); StyleConstants.setBold(s, true);
s = textPane.addStyle("large", regular); StyleConstants.setFontSize(s, 16); }
//method to add new text to the JTextPane public JTextPane addTextToTextPane() { Document doc = textPane.getDocument(); try { //clear previous text doc.remove(0,doc.getLength());
//insert title doc.insertString(0,"\tGRADES",textPane.getStyle("large"));
//insert detail for (int j = 0; j<grades.length; j++) { doc.insertString(doc.getLength(), "\n" + grades[j], textPane.getStyle("regular")); } if (average>0) { doc.insertString(doc.getLength(), "\nThe average of the grades is " + average, textPane.getStyle("regular")); } } catch (BadLocationException ble) { System.err.println("Couldn't insert text."); }
return textPane; }
//event to process user clicks public void actionPerformed(ActionEvent e) { String arg = e.getActionCommand(); if (arg == "Insert") { gTotal=0; average=0; Average=0; grades=new int[0]; //accept new data int newGrade=0,x=0; while (newGrade != -1) { String newGrades = JOptionPane.showInputDialog(null, "Please enter the new grades, and -1 if you are done entering data"); newGrade = Integer.parseInt(newGrades);
//add new data to arrays if (newGrade>0) { grades = enlargeArray(grades); grades[grades.length-1] = newGrade; x=x+1; gTotal=gTotal+newGrade; } else if (x==50) { JOptionPane.showMessageDialog(null, "You have entered the maximum amount of grades", "Error",JOptionPane.INFORMATION_MESSAGE);
newGrade=-1; } } DecimalFormat grade = new DecimalFormat("0"); average=gTotal/x; float Average = Float.parseFloat(grade.format(average)); Average=Average; sort(grades); } } //method to sort arrays public void sort(int tempArray[]) { //loop to control number of passes for (int pass = 1; pass < tempArray.length; pass++) { for (int element = 0; element < tempArray.length - 1; element++) if (tempArray[element] > tempArray[element + 1]) { swap(grades, element, element + 1); } } addTextToTextPane(); }
//method to swap two elements of an array public void swap(int swapArray[], int first, int second) { int hold; //temporary holding area for swap hold = swapArray[first]; swapArray[first] = swapArray[second]; swapArray[second] = hold; } //method to enlarge an array by 1 public int[] enlargeArray(int[] currentArray) { int[] newArray = new int[currentArray.length+1]; for(int i = 0; i<currentArray.length; i++) newArray[i] = currentArray[i];
return newArray; }
//main method executes at run time public static void main(String args[]) { JFrame.setDefaultLookAndFeelDecorated(true); Ch7Ex4 f = new Ch7Ex4(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(f.createMenuBar()); f.setContentPane(f.createContentPane()); f.setSize(725,300); f.setVisible(true); } }
Patricia Shanahan - 03 Mar 2007 03:22 GMT >> I need to round a float to the nearest whole number using >> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 4 lines] > OK, I'll show my code I guess... > Try compiling ...
> DecimalFormat grade = new DecimalFormat("0"); > average=gTotal/x; > float Average = Float.parseFloat(grade.format(average)); > Average=Average; > sort(grades); ...
This seems to be the only use of DecimalFormat in your code, and you only use the result for initializing the local variable Average, which you then assign to itself.
Maybe you meant to assign Average to some non-local variable, or make some other use of it?
Patricia
Don - 03 Mar 2007 03:32 GMT > >> I need to round a float to the nearest whole number using > >> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 23 lines] > > - Show quoted text - Um...no, no other uses for Average. It's just there so I can display it in the content pane after the grades are entered
Patricia Shanahan - 03 Mar 2007 03:49 GMT >>>> I need to round a float to the nearest whole number using >>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 24 lines] > Um...no, no other uses for Average. It's just there so I can display > it in the content pane after the grades are entered I don't know what you mean by "other" uses for Average. The Average declared in the quoted code has no uses at all, other than the extremely suspicious assignment to itself.
The class Ch7Ex4 also has member fields called "average" and "Average", but I don't see any use of DecimalFormat that gets anywhere near either of those.
Patricia
Don - 03 Mar 2007 04:03 GMT > >>>> I need to round a float to the nearest whole number using > >>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 36 lines] > > - Show quoted text - Ahem...suspicious? How the heck is this suspicious? Well anyway, you're the only one posting and you're not even helping for that matter, so I'm going to stop checking this thread. I don't see a point in reading criticism that doesn't even make sense at all. If someone out there has useful* advice, feel free to email me and tell me. thank you all for your time
Chris Uppal - 03 Mar 2007 04:30 GMT > Ahem...suspicious? How the heck is this suspicious? Well anyway, > you're the only one posting and you're not even helping for that > matter, so I'm going to stop checking this thread. I don't see a point > in reading criticism that doesn't even make sense at all. If someone > out there has useful* advice, feel free to email me and tell me. thank > you all for your time Wahey! As complete f.cking w.nkers go, this guy takes the week's biscuit!
...with considerable aplomb.
(He won't be reading this thread, and thus will never see my comments here -- which is fortunate, 'cos I would /hate/ to insult a beginner...)
-- chris
Knute Johnson - 03 Mar 2007 05:20 GMT >> Ahem...suspicious? How the heck is this suspicious? Well anyway, >> you're the only one posting and you're not even helping for that [quoted text clipped - 4 lines] > > Wahey! As complete f.cking w.nkers go, this guy takes the week's biscuit! Chocolate biscuit!
 Signature Knute Johnson email s/nospam/knute/
Don - 03 Mar 2007 22:18 GMT On Mar 2, 11:30 pm, "Chris Uppal" <chris.up...@metagnostic.REMOVE- THIS.org> wrote:
> > Ahem...suspicious? How the heck is this suspicious? Well anyway, > > you're the only one posting and you're not even helping for that [quoted text clipped - 11 lines] > > -- chris Please try to refrain from using offensive language. I wouldn't like anyone's eyes to be hurt reading such content.
Don - 03 Mar 2007 22:28 GMT On Mar 2, 11:30 pm, "Chris Uppal" <chris.up...@metagnostic.REMOVE- THIS.org> wrote:
> > Ahem...suspicious? How the heck is this suspicious? Well anyway, > > you're the only one posting and you're not even helping for that [quoted text clipped - 11 lines] > > -- chris And don't worry about insulting me, you only caused me to believe that you're a jagoff
Patricia Shanahan - 03 Mar 2007 05:43 GMT >>>>>> I need to round a float to the nearest whole number using >>>>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 37 lines] > out there has useful* advice, feel free to email me and tell me. thank > you all for your time I'm afraid that means the problem goes deeper than I thought. I assumed it was just a typo, compounded by poor choice of identifiers. Indeed it can be fixed by a one character change. However, if it had been simply a typo, Dan would have been able to find it from my hints.
I'm afraid it looks more like either a serious lack of understanding or inability to read the code as written, rather than as intended. Pity.
Patricia
Lew - 03 Mar 2007 14:52 GMT > I'm afraid it looks more like either a serious lack of understanding or > inability to read the code as written, rather than as intended. Pity. It is unfortunate that the OP took your advice as "criticism" (strange, since they explicitly asked what was wrong with their code then got upset when you told them). They missed the fact that you had pointed them to the problem and that addressing the issues you mentioned would have solved at least part of their difficulty.
OTOH, if they don't even know what a Java literal is by Chapter 7, then either the book, the instructor or the student is seriously flawed.
I just don't understand why they got mad when you gave the exact help requested.
Pity.
-- Lew
Don - 03 Mar 2007 22:07 GMT > > I'm afraid it looks more like either a serious lack of understanding or > > inability to read the code as written, rather than as intended. Pity. [quoted text clipped - 13 lines] > > -- Lew Well about the Java literal comment...my instructor doesn't really teach. We sorta just sit there, try some programs, and he sometimes summarizes a few pages
tomzam@gmail.com - 03 Mar 2007 17:17 GMT > >>>>>> I need to round a float to the nearest whole number using > >>>>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 47 lines] > > Patricia I'd like to point out that the word "suspicious" could have been interpreted in a legal sense of "wrongdoing" instead of the sense of programming code being incorrect. And the OP may have taken the former meaning as an insult. I, sent an email to the OP, hoping to clarify the matter as well as posting here. Finally, IMHO the OP needs to learn some more Java, becasue who in their right mind accuses Patrica of not being helpfull? Tom Z.
Patricia Shanahan - 03 Mar 2007 17:46 GMT >>>>>>>> I need to round a float to the nearest whole number using >>>>>>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 47 lines] > the sense of programming code being incorrect. And the OP may > have taken the former meaning as an insult. Good point. I meant "Something I suspect of being the cause of the bug".
> I, sent an email to the OP, hoping to clarify the matter as well as > posting here. > Finally, IMHO the OP needs to learn some more Java, becasue who in > their right mind accuses Patrica of not being helpfull? > Tom Z. I think also the OP may not have grasped the implication of earlier replies indicating that DecimalFormat works as expected. I was assuming the focus had shifted from the format to the logic of the surrounding code. The OP may still have been thinking DecimalFormat, and seen my comments about what happens afterwards as being irrelevant.
Patricia
Don - 03 Mar 2007 22:16 GMT > >>>> I need to round a float to the nearest whole number using > >>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 36 lines] > > - Show quoted text - And... I'm sorry about the "Average=Average;" part, I meant to use that to try out "f" with Average=Average f; or something like that, when it came up with an error I just erased the "f" and forgot about the "Average=Average;" Also, I meant to use have "doc.insertString(doc.getLength(), "\nThe average of the grades is " + Average, textPane.getStyle("regular"));" instead of the "doc.insertString(doc.getLength(), "\nThe average of the grades is " + average, textPane.getStyle("regular"));" which I believe I posted.
Patricia Shanahan - 03 Mar 2007 22:55 GMT >>>>>> I need to round a float to the nearest whole number using >>>>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 40 lines] > the grades is " + average, textPane.getStyle("regular"));" which I > believe I posted. In the code as posted, you have two different variables called "Average". One an instance variable, declared in the line:
float average,gTotal,Average;
The other is a local variable declared:
float Average = Float.parseFloat(grade.format(average));
Its scope is from its declaration to the end of the block, inside actionPerformed. Within its scope, the local variable "Average" hides the instance field "Average".
My first interpretation of "Average = Average;" was that you meant to have a separate local variable and assign it to either this.Average or average. I think maybe you are not aware that you have two different variables, and expect changes to Average in actionPerformed to operate on the same Average as your display code.
At a higher level, I'm curious about why you chose to convert the String result of format back to a float, rather than using it more directly in the display. It has the undesirable side effect of displaying values that are accurate to zero decimal places with one decimal place: 3.0 rather than just 3.
Patricia
Don - 03 Mar 2007 23:06 GMT > >>>>>> I need to round a float to the nearest whole number using > >>>>>> DecimalFormat (specific requirements for a program). I have tried [quoted text clipped - 69 lines] > > - Show quoted text - Oh, I didn't realize that that was why that was happening. I don't exactly remember why I did that; I wrote that part a week or two ago last time we had class. (My teachers went on strike for 7 days.) I've changed the code now, I'll post it after I check it for more mistakes and/or useless code.
By the way, is there any way to make 3.5 round up to 4 instead of 3, or is that just how DecimalFormat formats?
Patricia Shanahan - 03 Mar 2007 23:30 GMT ...
> By the way, is there any way to make 3.5 round up to 4 instead of 3, > or is that just how DecimalFormat formats? I don't really understand this question because 3.5 does round up to 4. In general, x.5 will round to the even number, so 2.5 rounds to 2, and both 3.5 and 4.5 round to 4.
You can get much more control over the rounding of a floating point number by converting it to BigDecimal and setting the scale with a specified rounding mode. You may want ROUND_HALF_UP, 'Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.'
Patricia
Don - 04 Mar 2007 00:16 GMT > ... > [quoted text clipped - 12 lines] > > Patricia Oh, I was just using 3.5 as an example, I didn't actually try entering it. So DecimalFormat will always round towards the even number? Because the requirements for the program specifically said to use DecimalFormat.
Mike Schilling - 04 Mar 2007 02:01 GMT > Oh, I was just using 3.5 as an example, I didn't actually try entering > it. So DecimalFormat will always round towards the even number? > Because the requirements for the program specifically said to use > DecimalFormat. The requirements for the program named a class to use. That's interesting. Is this by any chance a school assignment?
Karl Uppiano - 04 Mar 2007 01:58 GMT [big snip]
> By the way, is there any way to make 3.5 round up to 4 instead of 3, > or is that just how DecimalFormat formats? Not to be a jerk or anything, but this is an extremely useful reference: http://java.sun.com/javase/6/docs/api/index.html
and more specifically this: http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html#setRoundingMo de(java.math.RoundingMode)
and this: http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
Patricia Shanahan - 04 Mar 2007 02:15 GMT > [big snip] > [quoted text clipped - 8 lines] > > and this: http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html That is nice! Unfortunately not available in 1.5 or earlier, but a much more direct approach than converting to BigDecimal.
Patricia
murari garg - 04 Mar 2007 08:23 GMT > I need to round a float to the nearest whole number using > DecimalFormat (specific requirements for a program). I have tried > DecimalFormat grade = new DecimalFormat("0"); > but it does nothing at all. What should I put in the parentheses to > just round to the nearest whole number? class float { public static void main(String[] args) { float value = 12.33; DecimalFormat grade = new DecimalFormat("0"); System.out.println(grade.format(value)); }
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|