How can I allow input of different decimal symbols, say, 314,4 vs 314.4? And how can I get the value as a number?

Joe Sam Shirah

The general answer to this is to use NumberFormat and its methods format() and parse(). This will handle the default locale for you. You can also set up a NumberFormat for other locales. Demos are available in The Java Tutorial and elsewhere, but are generally display only, so I've included some basic code below.

To use the sample, key in a number and press "GO". The input will be formatted with the default locale, the "Display" field will format with a German locale, and the "Parsed" field shows the unformatted number obtained from parsing the String in the "Display" field.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;

public class JNFDP extends JFrame
                   implements ActionListener,
                              WindowListener
{
  NumberFormat nfLocal = 
    NumberFormat.getNumberInstance();
  NumberFormat nfGermany = 
    NumberFormat.getNumberInstance(
      Locale.GERMANY);

  JButton    jb = new JButton( "Go" );
  JLabel     jlI = new JLabel("Input a Number:"),
             jlD = new JLabel("Display:"),
             jlP = new JLabel("Parsed:");

  JPanel     jp = new JPanel();

  JTextField jtI = new JTextField( 10 ),
             jtD = new JTextField( 10 ),
             jtP = new JTextField( 10 );


  public JNFDP()
  {
    super( "JNFDP" );
    addWindowListener( this );

    jb.addActionListener( this );

    jp.add(jlI);
    jp.add(jtI);
    jp.add(jb);
    jp.add(jlD);
    jp.add(jtD);
    jp.add(jlP);
    jp.add(jtP);

    getContentPane().add( jp, BorderLayout.CENTER );
    pack();
    show();

  }  // end constructor


  // ActionListener Implementation
  public void actionPerformed(ActionEvent e)
  {
    jtD.setText( "" );
    jtP.setText( "" );
    try
    {
      Number n = nfLocal.parse( jtI.getText() );
      jtI.setText( nfLocal.format( n ) );
      jtD.setText( nfGermany.format( n ) );
      n = nfGermany.parse( jtD.getText() );
      jtP.setText( n.toString() );
    }
    catch( ParseException pe ) { jtI.setText( "" ); }

  }  // End actionPerformed


// Window Listener Implementation
  public void windowOpened(WindowEvent e) {}
  public void windowClosing(WindowEvent e)
  {
    dispose();
    System.exit(0);
  }
  public void windowClosed(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
// End Window Listener Implementation


  public static void main(String[] args)
  {
    new JNFDP();
  }

}  // end class JNFDP

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact