Please help with decimal format


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 13 of 13

Thread: Please help with decimal format

  1. #1
    Join Date
    May 2004
    Posts
    37

    Please help with decimal format

    Hello,

    I am trying to allow a user to set the number of zeros that come after the decimal point.

    I have been working at this for a while now and I can't get it figured out.

    I already have an existing Rational class that I wrote. Here is my RationalTester class.

    I tried to post the code, but it is too long (exceeds 10000 characters). I have attached the file. I almost broke the program up into two seperate postings, but I didn't know if that was a good idea or not.

    Thanks,
    Eric
    Attached Files Attached Files

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    Make sure that you keep your DecimalFormat objects and your decimalPlaces variables in sync. For example:
    Code:
    public class Tester {
      private int decimalPlaces;
      private DecimalFormat decimalFormat;
    
      public void setNumberOfDigits(int nod) {
        decimalPlaces = nod;
        String format = "#.";
        while( nod-- > 0 ) {
           format = format + "0";
        }
        decimalFormat = new DecimalFormat(format);
        // after you call this function, make sure you update the numbers that you are printing.
      }
    }
    Hope this helps.
    ~evlich

  3. #3
    Join Date
    May 2004
    Posts
    37

    Quick Question

    I will take a look at the recommendation.

    What is the arrow? "-->"

    Also is there a certain place that you should declare "format"?

    Thanks,
    Eric

  4. #4
    Join Date
    Aug 2003
    Posts
    313
    Sorry, the "-- >" isn't an "arrow" it is "nod--" is greater than 0. The "--" is shorthand for decrement variable after returning. For example:
    Code:
    int i = 0; //  Before   After    Value
    i++;       //    0          1          0
    ++i;       //    1          2          2
    i--;        //    2          1          2
    --i;        //    1          0          0
    The variable "format" is a temporary that is used to create the pattern for displaying numbers. It should be declared inside the function as shown in the example. "decimalFormat" should be declared as a class member.

    Hope this helps.
    ~evlich

  5. #5
    Join Date
    Mar 2005
    Posts
    20

    Ok

    OK, I already know about the increment/decrement operations.

    Sorry, I just wasn't reading it right.

    I took C++ a while back and it reminded me of pointers.

    I just thought it was something that I hadn't learned yet in Java.

    Thanks for the clarification.

    Eric

  6. #6
    Join Date
    Mar 2005
    Posts
    20

    Trying to keep it simple.

    OK, I have created a new class to just test decimal format.

    I must be doing something wrong.

    Thanks,
    Eric

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import java.lang.*;
    import javax.swing.*;
    
    public class DecimalFormatTester extends JFrame
    { 
    	private int decimalPlaces; 
    	private DecimalFormat decimalFormat; 
    	private String userDigits = "";
    	private JTextField decimalFormatField;
    	private String output = "";
    	JTextArea outputArea;
    		
    	public DecimalFormatTester()
    	{
    		super( "Using Decimal Format" );
    		
    		Container container = getContentPane();
    		container.setLayout( new FlowLayout() );
    		
    		outputArea = new JTextArea();
    			
    		JLabel decimalFormatLabel = new JLabel( "     Decimal Points" );
    		decimalFormatField = new JTextField( 10 );
    		
    		decimalFormatField.addActionListener
    		(
    			new ActionListener()	// anonymous inner class
    			{
    				// read value from user
    				public void actionPerformed( ActionEvent event )
    				{ 
    					setNumberOfDigits( Integer.parseInt( decimalFormatField.getText() ) );
    					String decimalPlacesArray[] = new String[ decimalPlaces ];
    					for( int counter = 0; counter < decimalPlacesArray.length; counter++ )
    					{
    						decimalPlacesArray[ counter ] = "0";
    					}
    					String decimalString = "";
    					for( int counter = 0; counter < decimalPlacesArray.length; counter++ )
    					{
    						decimalString += decimalPlacesArray[ counter ];
    					}
    					userDigits = "." + decimalString;
    					setNumberOfDigits( decimalPlaces );
    				}
    			} // end anonymous inner class
    		); // end call to addActionListener
    		
    		
    		container.add( decimalFormatLabel ); 
    		container.add( decimalFormatField );
    		container.add( outputArea );
    		
    		
    		setSize(420, 125 );
    		setVisible( true );
    	}
    
    	public void setNumberOfDigits(int nod) 
    	{ 
    		decimalPlaces = nod; String format = "#."; 
    		while( nod-- > 0 ) 
    		{ 
    			format = format + "0"; 
    		} 
    		decimalFormat = new DecimalFormat(format); 
    		// after you call this function, make sure you update the numbers that you are printing. 
    	} 
    	
    	private void displayResult( String operation )
    	{					
    		output += "uD1 " + decimalPlaces;
    		displayOutput();			
    	}
    	
    	private void displayOutput()
    	{
    		outputArea.setText( output );	
    	}
    
    	public static void main( String args[] )
    	{
    		DecimalFormatTester dft = new DecimalFormatTester();  
    		dft.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    	}
    }

  7. #7
    Join Date
    Mar 2005
    Posts
    20
    OK, I know two things I didn't have correct. I wasn't invoking method displayResult and I wasn't parsing the int to a string.

    I am still not getting the expected results.

    Eric

  8. #8
    Join Date
    Aug 2003
    Posts
    313
    I couldn't figure out what some of the code was trying to do. But it didn't seem like you were actually using the DecimalFormat object. Here's the code that I changed:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import java.lang.*;
    import javax.swing.*;
    
    public class DecimalFormatTester extends JFrame
    {
    	private int decimalPlaces;
    	private DecimalFormat decimalFormat;
    	private String userDigits = "";
    	private JTextField decimalFormatField;
    	private String output = "";
    	JTextArea outputArea;
    
    	public DecimalFormatTester()
    	{
    		super( "Using Decimal Format" );
    
    		Container container = getContentPane();
    		container.setLayout( new FlowLayout() );
    
    		outputArea = new JTextArea();
    
    		JLabel decimalFormatLabel = new JLabel( "     Decimal Points" );
    		decimalFormatField = new JTextField( 10 );
    
            // Text fields don't post action events, so try binding on key events.
            decimalFormatField.addKeyListener(new KeyListener() {
    
                public void keyTyped(KeyEvent e) {
                }
    
                public void keyPressed(KeyEvent e) {
                }
    
                public void keyReleased(KeyEvent e) {
                    if( e.getKeyCode() == KeyEvent.VK_ENTER ) {
                        System.out.println("Here");
                        setNumberOfDigits( Integer.parseInt( decimalFormatField.getText() ) );
    
                        output = decimalFormat.format(Math.PI);
                        displayOutput();
                        
                        // I don't know what you are trying to do here
                        /*
    					String decimalPlacesArray[] = new String[ decimalPlaces ];
    					for( int counter = 0; counter < decimalPlacesArray.length; counter++ )
    					{
    						decimalPlacesArray[ counter ] = "0";
    					}
    					String decimalString = "";
    					for( int counter = 0; counter < decimalPlacesArray.length; counter++ )
    					{
    						decimalString += decimalPlacesArray[ counter ];
    					}
    					userDigits = "." + decimalString;
    					setNumberOfDigits( decimalPlaces );*/
                    }
                }
            });
    
    		container.add( decimalFormatLabel );
    		container.add( decimalFormatField );
    		container.add( outputArea );
    
    
    		setSize(420, 125 );
    		setVisible( true );
    	}
    
    	public void setNumberOfDigits(int nod)
    	{
    		decimalPlaces = nod; String format = "#.";
    		while( nod-- > 0 )
    		{
    			format = format + "0";
    		}
    		decimalFormat = new DecimalFormat(format);
    		// after you call this function, make sure you update the numbers that you are printing.
    	}
    
    	private void displayResult( String operation )
    	{
    		output += "uD1 " + decimalPlaces;
    		displayOutput();
    	}
    
    	private void displayOutput()
    	{
    		outputArea.setText( output );
    	}
    
    	public static void main( String args[] )
    	{
    		DecimalFormatTester dft = new DecimalFormatTester();
    		dft.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    	}
    }
    If you have any questions, just post them.

    Hope this helps.
    ~evlich

  9. #9
    Join Date
    Mar 2005
    Posts
    20

    I was trying to use an array.

    Code:
    // I don't know what you are trying to do here 
    /* String decimalPlacesArray[] = new String[ decimalPlaces ]; 
    for( int counter = 0; counter < decimalPlacesArray.length; counter++ ) 
    { 
                 decimalPlacesArray[ counter ] = "0"; 
    } 
    String decimalString = ""; 
    for( int counter = 0; counter < decimalPlacesArray.length; counter++ ) 
    { 
    	decimalString += decimalPlacesArray[ counter ]; 
    } 
    userDigits = "." + decimalString; 
    setNumberOfDigits( decimalPlaces );
    */

    My initial thought was that I would need an array of decimal places. Is there a way to use the approach that I was taking?

    I am looking over the code that you posted. Does KeyEvent.VK_ENTER listen for the enter key? What is VK?

    Thank you so much for clearing this up for me.

    Eric

  10. #10
    Join Date
    Mar 2005
    Posts
    20
    In reference to the code that you posted, you are using Math.PI, so method displayResult( String operation ) never gets invoked.

    In order for me to use the input from the user, I would have to use decimalPlaces in place of Math.PI.

    Am I reading this right?

    Thanks,
    Eric

  11. #11
    Join Date
    Mar 2005
    Posts
    20

    A little confused.

    OK, now I'm a little confused.

    I do understand that method displayResult( String operation ) is not used at all because the output is set inside method keyReleased ( KeyEvent e ).

    So to make sure I know what is going on, I changed

    output = decimalFormat.format( Math.PI );

    to

    output = decimalFormat.format( decimalPlaces );

    The program is displaying the number of zeros that the user inputs.
    The program is also displaying the input number to the left of the decimal.

    Is this just because the new decimal format has not been used to set the decimal place of any other variable yet?

    I guess my question is that I do not understand how the actual number that the user inputs is being assigned to the left of the decimal.

    Thanks,
    Eric

  12. #12
    Join Date
    Mar 2005
    Posts
    20
    OK, please let me know if I am understanding this correctly.

    DecimalFormat uses patterns.

    In the code that you posted, the pattern is "#.".

    So the # is the number that the user enters.

    Is that right?

    How do I use this to apply it to a sum of two fractions or something similar?
    I am wanting to be able to let a user input two rational numbers (two numerators and two denominator), and enter the number of decimal places they prefer to see. Then the user can add, subtract, multiply, or divide the two fractions. I have everything working except for this part. I just want to understand how this works. Sorry for all the questions.

    Thanks,
    Eric

    Thanks,
    Eric

  13. #13
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Why don't you have look at the documentation for DecimalFormat ? All patterns are
    explained there. E.g. '#' is the pattern for one digit that displays as <blank> when absent.

    '####.###' would display PI as '3,14'
    '0000.000' would display PI as '0003,141'

    You just need the code for building the pattern string based on the users input.

    As for your last question you need two textfields and a set of radiobuttons
    for selecting the operator.

    PS: there is a definite limit to how precise a decimal number can be displayed when
    using standard mathematical operators for calculation.
    Last edited by sjalle; 07-24-2005 at 08:05 AM.
    eschew obfuscation

Similar Threads

  1. IIS Extended Format
    By Sean Newton in forum Web
    Replies: 1
    Last Post: 11-15-2006, 04:53 AM
  2. Conversion of decimal in Oracle to Access 2000
    By Villy Olsson in forum Database
    Replies: 4
    Last Post: 04-06-2002, 09:01 PM
  3. VB, Regional Settings, and Access
    By Greg Rothlander in forum VB Classic
    Replies: 4
    Last Post: 12-13-2000, 01:11 AM
  4. Replies: 0
    Last Post: 12-04-2000, 02:25 PM
  5. BCP Format File
    By Chris H in forum Database
    Replies: 1
    Last Post: 09-27-2000, 11:03 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center