Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > How to Round a float to an nearest whole number

Reply
Thread Tools

How to Round a float to an nearest whole number

 
 
Don
Guest
Posts: n/a
 
      03-03-2007
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?

 
Reply With Quote
 
 
 
 
Knute Johnson
Guest
Posts: n/a
 
      03-03-2007
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

--

Knute Johnson
email s/nospam/knute/
 
Reply With Quote
 
 
 
 
Don
Guest
Posts: n/a
 
      03-03-2007
On Mar 2, 8:42 pm, Knute Johnson <(E-Mail Removed)>
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));
> }
>
> }
>
> C:\>java test3
> 2
>
> --
>
> Knute Johnson
> email s/nospam/knute/


What does the "f" for?

 
Reply With Quote
 
Joshua Cranmer
Guest
Posts: n/a
 
      03-03-2007
Don wrote:
> On Mar 2, 8:42 pm, Knute Johnson <(E-Mail Removed)>
> 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));
>> }
>>
>> }
>>
>> C:\>java test3
>> 2
>>
>> --
>>
>> Knute Johnson
>> email s/nospam/knute/

>
> What does the "f" for?
>

The 'f' makes it a float literal and not a double (which a floating
point is by default).
 
Reply With Quote
 
Don
Guest
Posts: n/a
 
      03-03-2007
On Mar 2, 9:01 pm, Joshua Cranmer <(E-Mail Removed)> wrote:
> Don wrote:
> > On Mar 2, 8:42 pm, Knute Johnson <(E-Mail Removed)>
> > 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));
> >> }

>
> >> }

>
> >> C:\>java test3
> >> 2

>
> >> --

>
> >> Knute Johnson
> >> email s/nospam/knute/

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

 
Reply With Quote
 
Patricia Shanahan
Guest
Posts: n/a
 
      03-03-2007
Don wrote:
> On Mar 2, 9:01 pm, Joshua Cranmer <(E-Mail Removed)> wrote:
>> Don wrote:
>>> On Mar 2, 8:42 pm, Knute Johnson <(E-Mail Removed)>
>>> 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
 
Reply With Quote
 
=?ISO-8859-1?Q?Arne_Vajh=F8j?=
Guest
Posts: n/a
 
      03-03-2007
Don wrote:
> On Mar 2, 8:42 pm, Knute Johnson <(E-Mail Removed)>
> wrote:
>> float value = 1.9f;


> What does the "f" for?


float (as in "not double").

Arne
 
Reply With Quote
 
Don
Guest
Posts: n/a
 
      03-03-2007
On Mar 2, 8:27 pm, "Don" <(E-Mail Removed)> 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?


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(Sty leContext.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("l arge"));

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

 
Reply With Quote
 
Patricia Shanahan
Guest
Posts: n/a
 
      03-03-2007
Don wrote:
> On Mar 2, 8:27 pm, "Don" <(E-Mail Removed)> 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?

>
> 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
 
Reply With Quote
 
Don
Guest
Posts: n/a
 
      03-03-2007
On Mar 2, 10:22 pm, Patricia Shanahan <(E-Mail Removed)> wrote:
> Don wrote:
> > On Mar 2, 8:27 pm, "Don" <(E-Mail Removed)> 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?

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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
round down to nearest number noydb Python 14 02-11-2012 10:26 AM
float to string to float, with first float == second float Carsten Fuchs C++ 45 10-08-2009 09:47 AM
round number to nearest integer. Fred Java 3 06-06-2004 06:20 AM
round up to nearest number and significant figures Steve Java 5 05-17-2004 01:30 AM
Re: float->byte->float is same with original float image. why float->ubyte->float is different??? bd C Programming 0 07-07-2003 12:09 AM



Advertisments