How to Round a float to an nearest whole number

D

Don

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?
 
K

Knute Johnson

Don said:
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
 
D

Don

Don said:
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

What does the "f" for?
 
J

Joshua Cranmer

Don said:
Don said:
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

What does the "f" for?
The 'f' makes it a float literal and not a double (which a floating
point is by default).
 
D

Don

Don said:
Don wrote:
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
What does the "f" for?

The 'f' makes it a float literal and not a double (which a floating
point is by default).- Hide quoted text -

- Show quoted text -

So would I need to use "f" when formatting a variable? If so, how
would I do that?
 
P

Patricia Shanahan

Don said:
Don said:
On Mar 2, 8:42 pm, Knute Johnson <[email protected]>
wrote:
Don wrote:
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));
}
}
....
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
 
D

Don

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 = currentArray;

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);
}
}
 
P

Patricia Shanahan

Don said:
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
 
D

Don

...

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- Hide quoted text -

- 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
 
P

Patricia Shanahan

Don said:
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
 
D

Don

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- Hide quoted text -

- 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
 
C

Chris Uppal

Don said:
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 fucking wankers 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
 
P

Patricia Shanahan

Don said:
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

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
 
L

Lew

Patricia said:
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
 
T

tomzam

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


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.
 
P

Patricia Shanahan

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.

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
 
D

Don

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top