How do I display and parse currency values?

Joe Sam Shirah

The short answer is to use Numberformat.getCurrencyInstance(), then use the format() and parse() methods. I have included a non-production quality code sample that accepts input in one's local currency, then parses and displays the value both as German marks and purely as a number. The code is similiar to other programs that use NumberFormats, but I want to mention selected issues:

The first is a parsing issue often seen regarding NumberFormats: The parser adheres fairly strictly to a given pattern, which doesn't always jibe with real world needs. For example, we probably wouldn't want to force the user to always key in a leading $ sign for US currency or a trailing space and "DM" for marks on input, but just keying in, say, 50, will give an exception out of the box. This code handles the situation by getting the locale's currency symbol and concatenating it to the input text, if no currency symbol was keyed, before parse() is invoked. Not gospel, just one method.

Next, a currency symbol may be a prefix or a suffix. The code determines this by checking the position of the currency sign in the DecimalFormat's pattern and concatenating the currency symbol accordingly.

Last, if one keys 100 in a US locale, one sees $100.00 and 100,00 DM displayed. Keep in mind that xxxFormats only format a given number. If you want the real equivalent of $100 in marks, you'll have to have some currency conversion information. Otherwise, even in your default locale, you may need a foreign locale to keep the values comprehensible. For example, when reporting earnings of a German subsidiary of a US company to US readers, you probably want to set the DecimalFormat to a German locale so the viewer understands that they are seeing a value in marks, not dollars. Even there, you may want to use US style commas and decimal points.


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

public class JCFDP extends JFrame
                   implements ActionListener,
                              WindowListener
{
  boolean    bPre = true;
  int        ndx = 0;

  JButton    jb = new JButton( "Go" );
  JLabel     jlI = new JLabel("Input Currency Value:"),
             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 );

  NumberFormat cfLocal = NumberFormat.getCurrencyInstance();
  NumberFormat cfGermany = NumberFormat.
                 getCurrencyInstance(Locale.GERMANY);

  String sCurSymbol = "";


  public JCFDP()
  {
    super( "JCFDP" );
    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();

    if( cfLocal instanceof DecimalFormat )
    { // determine if symbol is prefix or suffix
      DecimalFormatSymbols dfs =
          ((DecimalFormat)cfLocal).getDecimalFormatSymbols();
      sCurSymbol = dfs.getCurrencySymbol();
      String sLP = ((DecimalFormat)cfLocal).toLocalizedPattern();
      ndx = sLP.indexOf( 'u00A4' );  // currency sign
      if( ndx > 0 ) { bPre = false; }
      else { bPre = true; }
    }

  }  // end constructor


  // ActionListener Implementation
  public void actionPerformed(ActionEvent e)
  {
    Number n = null;
    String sText = jtI.getText();

    jtD.setText( "" );
    jtP.setText( "" );

    ndx = sText.indexOf( sCurSymbol );
    if( ndx == -1 )
    { 
      if( bPre ) { sText = sCurSymbol + sText; }
      else       { sText = sText + " " + sCurSymbol; }
    }
    try
    {
      n = cfLocal.parse( sText );
      jtI.setText( cfLocal.format( n ) );
      jtD.setText( cfGermany.format( n ) );
      n = cfGermany.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 JCFDP();
  }

}  // end class JCFDP
Comment and Contribute

 

 

 

 

 


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

 

 

About | Sitemap | Contact