Java/Data Type/Number Format

Материал из Java эксперт
Версия от 06:19, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

A custom number formatter that formats numbers as hexadecimal strings.

    
/* 
 * JFreeChart : a free chart library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jfreechart/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * --------------------
 * HexNumberFormat.java
 * --------------------
 * (C) Copyright 2007, 2008, by Richard West and Contributors.
 *
 * Original Author:  Richard West, Advanced Micro Devices, Inc.;
 * Contributor(s):   David Gilbert (for Object Refinery Limited);
 *
 * Changes:
 * --------
 * 14-Jun-2007 : Version 1 (RW);
 *
 */
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
/**
 * A custom number formatter that formats numbers as hexadecimal strings.
 * There are some limitations, so be careful using this class.
 *
 * @since 1.0.6
 */
public class HexNumberFormat extends NumberFormat {
    /** Number of hexadecimal digits for a byte. */
    public static final int BYTE = 2;
    /** Number of hexadecimal digits for a word. */
    public static final int WORD = 4;
    /** Number of hexadecimal digits for a double word. */
    public static final int DWORD = 8;
    /** Number of hexadecimal digits for a quad word. */
    public static final int QWORD = 16;
    /** The number of digits (shorter strings will be left padded). */
    private int m_numDigits = DWORD;
    /**
     * Creates a new instance with 8 digits.
     */
    public HexNumberFormat() {
        this(DWORD);
    }
    /**
     * Creates a new instance with the specified number of digits.
     * @param digits  the digits.
     */
    public HexNumberFormat(int digits) {
        super();
        this.m_numDigits = digits;
    }
    /**
     * Returns the number of digits.
     *
     * @return The number of digits.
     */
    public final int getNumberOfDigits() {
        return this.m_numDigits;
    }
    /**
     * Sets the number of digits.
     *
     * @param digits  the number of digits.
     */
    public void setNumberOfDigits(int digits) {
        this.m_numDigits = digits;
    }
    /**
     * Formats the specified number as a hexadecimal string.  The decimal
     * fraction is ignored.
     *
     * @param number  the number to format.
     * @param toAppendTo  the buffer to append to (ignored here).
     * @param pos  the field position (ignored here).
     *
     * @return The string buffer.
     */
    public StringBuffer format(double number, StringBuffer toAppendTo,
            FieldPosition pos) {
        return format((long) number, toAppendTo, pos);
    }
    /**
     * Formats the specified number as a hexadecimal string.  The decimal
     * fraction is ignored.
     *
     * @param number  the number to format.
     * @param toAppendTo  the buffer to append to (ignored here).
     * @param pos  the field position (ignored here).
     *
     * @return The string buffer.
     */
    public StringBuffer format(long number, StringBuffer toAppendTo,
            FieldPosition pos) {
        String l_hex = Long.toHexString(number).toUpperCase();
        int l_pad = this.m_numDigits - l_hex.length();
        l_pad = (0 < l_pad) ? l_pad : 0;
        StringBuffer l_extended = new StringBuffer("0x");
        for (int i = 0; i < l_pad; i++) {
            l_extended.append(0);
        }
        l_extended.append(l_hex);
        return l_extended;
    }
    /**
     * Parsing is not implemented, so this method always returns
     * <code>null</code>.
     *
     * @param source  ignored.
     * @param parsePosition  ignored.
     *
     * @return Always <code>null</code>.
     */
    public Number parse (String source, ParsePosition parsePosition) {
        return null; // don"t bother with parsing
    }
}





Add leading zeroes to a number

    
 
public class Main {
  public static void main(String[] args) {
    int number = 1500;
    String formatted = String.format("%07d", number);
    System.out.println("Number with leading zeros: " + formatted);
  }
}





A number formatter for logarithmic values. This formatter does not support parsing.

    
/* 
 * JFreeChart : a free chart library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2009, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jfreechart/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
 * in the United States and other countries.]
 *
 * --------------
 * LogFormat.java
 * --------------
 * (C) Copyright 2007-2009, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * Changes
 * -------
 * 02-Aug-2007 : Version 1 (DG);
 * 19-Feb-2008 : Implemented equals() and clone(), and added new powerLabel
 *               attribute as per Feature Request 1886036 (DG);
 * 14-Jan-2009 : Added default constructor, and accessor methods for
 *               exponent formatter (DG);
 *
 */
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
/**
 * A number formatter for logarithmic values.  This formatter does not support
 * parsing.
 *
 * @since 1.0.7
 */
public class LogFormat extends NumberFormat {
    /** The log base value. */
    private double base;
    /** The natural logarithm of the base value. */
    private double baseLog;
    /** The label for the log base (for example, "e"). */
    private String baseLabel;
    /**
     * The label for the power symbol.
     *
     * @since 1.0.10
     */
    private String powerLabel;
    /** A flag that controls whether or not the base is shown. */
    private boolean showBase;
    /** The number formatter for the exponent. */
    private NumberFormat formatter = new DecimalFormat("0.0#");
    /**
     * Creates a new instance using base 10.
     *
     * @since 1.0.13
     */
    public LogFormat() {
        this(10.0, "10", true);
    }
    /**
     * Creates a new instance.
     *
     * @param base  the base.
     * @param baseLabel  the base label (<code>null</code> not permitted).
     * @param showBase  a flag that controls whether or not the base value is
     *                  shown.
     */
    public LogFormat(double base, String baseLabel, boolean showBase) {
        this(base, baseLabel, "^", showBase);
    }
    /**
     * Creates a new instance.
     *
     * @param base  the base.
     * @param baseLabel  the base label (<code>null</code> not permitted).
     * @param powerLabel  the power label (<code>null</code> not permitted).
     * @param showBase  a flag that controls whether or not the base value is
     *                  shown.
     *
     * @since 1.0.10
     */
    public LogFormat(double base, String baseLabel, String powerLabel,
            boolean showBase) {
        if (baseLabel == null) {
            throw new IllegalArgumentException("Null "baseLabel" argument.");
        }
        if (powerLabel == null) {
            throw new IllegalArgumentException("Null "powerLabel" argument.");
        }
        this.base = base;
        this.baseLog = Math.log(this.base);
        this.baseLabel = baseLabel;
        this.showBase = showBase;
        this.powerLabel = powerLabel;
    }
    /**
     * Returns the number format used for the exponent.
     *
     * @return The number format (never <code>null</code>).
     *
     * @since 1.0.13.
     */
    public NumberFormat getExponentFormat() {
        return (NumberFormat) this.formatter.clone();
    }
    /**
     * Sets the number format used for the exponent.
     *
     * @param format  the formatter (<code>null</code> not permitted).
     *
     * @since 1.0.13
     */
    public void setExponentFormat(NumberFormat format) {
        if (format == null) {
            throw new IllegalArgumentException("Null "format" argument.");
        }
        this.formatter = format;
    }
    /**
     * Calculates the log of a given value.
     *
     * @param value  the value.
     *
     * @return The log of the value.
     */
    private double calculateLog(double value) {
        return Math.log(value) / this.baseLog;
    }
    /**
     * Returns a formatted representation of the specified number.
     *
     * @param number  the number.
     * @param toAppendTo  the string buffer to append to.
     * @param pos  the position.
     *
     * @return A string buffer containing the formatted value.
     */
    public StringBuffer format(double number, StringBuffer toAppendTo,
            FieldPosition pos) {
        StringBuffer result = new StringBuffer();
        if (this.showBase) {
            result.append(this.baseLabel);
            result.append(this.powerLabel);
        }
        result.append(this.formatter.format(calculateLog(number)));
        return result;
    }
    /**
     * Formats the specified number as a hexadecimal string.  The decimal
     * fraction is ignored.
     *
     * @param number  the number to format.
     * @param toAppendTo  the buffer to append to (ignored here).
     * @param pos  the field position (ignored here).
     *
     * @return The string buffer.
     */
    public StringBuffer format(long number, StringBuffer toAppendTo,
            FieldPosition pos) {
        StringBuffer result = new StringBuffer();
        if (this.showBase) {
            result.append(this.baseLabel);
            result.append("^");
        }
        result.append(this.formatter.format(calculateLog(number)));
        return result;
    }
    /**
     * Parsing is not implemented, so this method always returns
     * <code>null</code>.
     *
     * @param source  ignored.
     * @param parsePosition  ignored.
     *
     * @return Always <code>null</code>.
     */
    public Number parse (String source, ParsePosition parsePosition) {
        return null; // don"t bother with parsing
    }
    /**
     * Tests this formatter for equality with an arbitrary object.
     *
     * @param obj  the object (<code>null</code> permitted).
     *
     * @return A boolean.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof LogFormat)) {
            return false;
        }
        LogFormat that = (LogFormat) obj;
        if (this.base != that.base) {
            return false;
        }
        if (!this.baseLabel.equals(that.baseLabel)) {
            return false;
        }
        if (this.baseLog != that.baseLog) {
            return false;
        }
        if (this.showBase != that.showBase) {
            return false;
        }
        if (!this.formatter.equals(that.formatter)) {
            return false;
        }
        return super.equals(obj);
    }
    /**
     * Returns a clone of this instance.
     *
     * @return A clone.
     */
    public Object clone() {
        LogFormat clone = (LogFormat) super.clone();
        clone.formatter = (NumberFormat) this.formatter.clone();
        return clone;
    }
}





Create a table of squares and cubes.

     
import java.util.Formatter;
class FieldWidthDemo {
  public static void main(String args[]) {
    Formatter fmt;
    for (int i = 1; i <= 10; i++) {
      fmt = new Formatter();
      fmt.format("%4d %4d %4d", i, i * i, i * i * i);
      System.out.println(fmt);
    }
  }
}





Decimal Format Demo

    
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DecimalFormatDemo extends JPanel {
  static JFrame frame;
  JLabel result;
  NumberFormat inputFormatter;
  String currentPattern;
  double currentNumber = 123.45;
  LocaleGroup availableLocales;
  public DecimalFormatDemo() {
    availableLocales = new LocaleGroup();
    inputFormatter = NumberFormat.getNumberInstance();
    String[] patternExamples = { "##.##", "###,###.##", "##,##,##.##", "#",
        "000,000.0000", "##.0000", ""hello"###.##" };
    currentPattern = patternExamples[0];
    // Set up the UI for entering a number.
    JLabel numberLabel = new JLabel("Enter the number to format:");
    numberLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
    JTextField numberField = new JTextField();
    numberField.setEditable(true);
    numberField.setAlignmentX(Component.LEFT_ALIGNMENT);
    NumberListener numberListener = new NumberListener();
    numberField.addActionListener(numberListener);
    // Set up the UI for selecting a pattern.
    JLabel patternLabel1 = new JLabel("Enter the pattern string or");
    JLabel patternLabel2 = new JLabel("select one from the list:");
    patternLabel1.setAlignmentX(Component.LEFT_ALIGNMENT);
    patternLabel2.setAlignmentX(Component.LEFT_ALIGNMENT);
    JComboBox patternList = new JComboBox(patternExamples);
    patternList.setSelectedIndex(0);
    patternList.setEditable(true);
    patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
    PatternListener patternListener = new PatternListener();
    patternList.addActionListener(patternListener);
    // Set up the UI for selecting a locale.
    JLabel localeLabel = new JLabel("Select a Locale from the list:");
    localeLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
    JComboBox localeList = new JComboBox(availableLocales.getStrings());
    localeList.setSelectedIndex(0);
    localeList.setAlignmentX(Component.LEFT_ALIGNMENT);
    LocaleListener localeListener = new LocaleListener();
    localeList.addActionListener(localeListener);
    // Create the UI for displaying result.
    JLabel resultLabel = new JLabel("Result", JLabel.LEFT);
    resultLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
    result = new JLabel(" ");
    result.setForeground(Color.black);
    result.setAlignmentX(Component.LEFT_ALIGNMENT);
    result.setBorder(BorderFactory.createCompoundBorder(BorderFactory
        .createLineBorder(Color.black), BorderFactory.createEmptyBorder(5, 5,
        5, 5)));
    // Lay out everything
    JPanel numberPanel = new JPanel();
    numberPanel.setLayout(new GridLayout(0, 1));
    numberPanel.add(numberLabel);
    numberPanel.add(numberField);
    JPanel patternPanel = new JPanel();
    patternPanel.setLayout(new BoxLayout(patternPanel, BoxLayout.Y_AXIS));
    patternPanel.add(patternLabel1);
    patternPanel.add(patternLabel2);
    patternPanel.add(patternList);
    JPanel localePanel = new JPanel();
    localePanel.setLayout(new BoxLayout(localePanel, BoxLayout.Y_AXIS));
    localePanel.add(localeLabel);
    localePanel.add(localeList);
    JPanel resultPanel = new JPanel();
    resultPanel.setLayout(new GridLayout(0, 1));
    resultPanel.add(resultLabel);
    resultPanel.add(result);
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    patternPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
    numberPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
    localePanel.setAlignmentX(Component.CENTER_ALIGNMENT);
    resultPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(numberPanel);
    add(Box.createVerticalStrut(10));
    add(patternPanel);
    add(Box.createVerticalStrut(10));
    add(localePanel);
    add(Box.createVerticalStrut(10));
    add(resultPanel);
    setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    reformat();
    numberField.setText(result.getText());
  } // constructor
  /** Listens to the pattern combo box. */
  class PatternListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      JComboBox cb = (JComboBox) e.getSource();
      String newSelection = (String) cb.getSelectedItem();
      currentPattern = newSelection;
      reformat();
    }
  }
  /** Listens to the number field. */
  class NumberListener implements ActionListener {
    public void actionPerformed(ActionEvent evt) {
      JTextField inputField = (JTextField) evt.getSource();
      try {
        Number value = inputFormatter.parse(inputField.getText());
        currentNumber = value.doubleValue();
        reformat();
      } catch (ParseException pe) {
        result.setForeground(Color.red);
        result.setText("Illegal Number: " + pe.getMessage());
      }
    }
  }
  /** Listens to the locale combo box. */
  class LocaleListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      JComboBox cb = (JComboBox) e.getSource();
      int index = cb.getSelectedIndex();
      availableLocales.setCurrent(index);
      reformat();
    }
  }
  /** Manages information about locales for this application. */
  class LocaleGroup {
    Locale currentLocale;
    Locale[] supportedLocales = { Locale.US, Locale.GERMANY, Locale.FRANCE
    // Add other locales here, if desired.
    };
    public LocaleGroup() {
      currentLocale = supportedLocales[0];
    }
    public void setCurrent(int index) {
      currentLocale = supportedLocales[index];
    }
    public Locale getCurrent() {
      return currentLocale;
    }
    public String[] getStrings() {
      String[] localeNames = new String[supportedLocales.length];
      for (int k = 0; k < supportedLocales.length; k++) {
        localeNames[k] = supportedLocales[k].getDisplayName();
      }
      return localeNames;
    }
  }
  /** Reformats the input number and displays result. */
  public void reformat() {
    try {
      NumberFormat nf = NumberFormat.getNumberInstance(availableLocales
          .getCurrent());
      DecimalFormat df = (DecimalFormat) nf;
      df.applyPattern(currentPattern);
      result.setForeground(Color.black);
      result.setText(df.format(currentNumber));
    } catch (IllegalArgumentException iae) {
      result.setForeground(Color.red);
      result.setText("Illegal Pattern: " + iae.getMessage());
    }
  }
  public static void main(String s[]) {
    WindowListener l = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    frame = new JFrame("DecimalFormat Demo");
    frame.addWindowListener(l);
    frame.getContentPane().add("Center", new DecimalFormatDemo());
    frame.pack();
    frame.setVisible(true);
  }
}





Default rounding mode

     
import java.math.RoundingMode;
import java.text.NumberFormat;
public class NumberFormatRounding {
  public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();
  }
}





demonstrates the minimum field-width specifier by applying it to the %f conversion:

     
// Demonstrate a field-width specifier.
import java.util.Formatter;
class FormatDemo4 {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("|%f|%n|%12f|%n|%012f|", 10.12345, 10.12345, 10.12345);
    System.out.println(fmt);
  }
}





demonstrates the %n and %% format specifiers:

     
import java.util.Formatter;
class FormatDemo3 {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("Copying file%nTransfer is %d%% complete", 88);
    System.out.println(fmt);
  }
}





Demonstrate the space format specifiers.

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("% d", -100);
    System.out.println(fmt);
    fmt = new Formatter();
    fmt.format("% d", 100);
    System.out.println(fmt);
    fmt = new Formatter();
    fmt.format("% d", -200);
    System.out.println(fmt);
    fmt = new Formatter();
    fmt.format("% d", 200);
    System.out.println(fmt);
  }
}
/*
-100
 100
-200
 200*/





Displaying numbers with commas

   
import java.text.DecimalFormat;
public class Main {
  public static void main(String args[]) {
    double d = 123456.78;
    DecimalFormat df = new DecimalFormat("#####0.00");
    System.out.println(df.format(d));
  }
}





Display numbers in scientific notation

   
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
  public static void main(String args[]) {
    NumberFormat formatter = new DecimalFormat();
    int maxinteger = Integer.MAX_VALUE;
    System.out.println(maxinteger); 
    formatter = new DecimalFormat("0.######E0");
    System.out.println(formatter.format(maxinteger));
    formatter = new DecimalFormat("0.#####E0");
    System.out.println(formatter.format(maxinteger));
    int mininteger = Integer.MIN_VALUE;
    System.out.println(mininteger); 
    formatter = new DecimalFormat("0.######E0");
    System.out.println(formatter.format(mininteger)); 
    formatter = new DecimalFormat("0.#####E0");
    System.out.println(formatter.format(mininteger));
    double d = 0.12345;
    formatter = new DecimalFormat("0.#####E0");
    System.out.println(formatter.format(d));
    formatter = new DecimalFormat("000000E0");
    System.out.println(formatter.format(d)); 
  }
}





Format a number for a locale

   
 
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] args) throws Exception {
    NumberFormat formatter = NumberFormat.getNumberInstance(Locale.ITALY);
    String number = formatter.format(123456789.12);
    System.out.println("Number in Italy: " + number);
    formatter = NumberFormat.getNumberInstance(Locale.JAPAN);
    number = formatter.format(123456789.12);
    System.out.println("Number in Japan: " + number);
  }
}





Format a number our way and the default way

    
import java.text.NumberFormat;
/*
 * Format a number our way and the default way.
 */
public class NumFormat2 {
  /** A number to format */
  public static final double data[] = {
    0, 1, 22d/7, 100.2345678
  };
  /** The main (and only) method in this class. */
  public static void main(String[] av) { 
    // Get a format instance
    NumberFormat form = NumberFormat.getInstance();
    // Set it to look like 999.99[99]
    form.setMinimumIntegerDigits(3);
    form.setMinimumFractionDigits(2);
    form.setMaximumFractionDigits(4);
    // Now print using it.
    for (int i=0; i<data.length; i++)
      System.out.println(data[i] + "\tformats as " +
        form.format(data[i]));
  }
}





Format a number to currency

    
import java.text.NumberFormat;
public class Mortgage {
  public static void main(String[] args) {
    double payment = Math.random() * 1000;
    System.out.println("Your payment is ");
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    System.out.println(nf.format(payment));
  }
}





Format a number with DecimalFormat

   
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
  public static void main(String[] args) {
    double money = 123456789.12;
    NumberFormat formatter = new DecimalFormat("#0.00");
    System.out.println(money);
    System.out.println(formatter.format(money));
  }
}





Format a number with leading zeroes

   
 
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
  public static void main(String[] args) {
    NumberFormat formatter = new DecimalFormat("0000000");
    String number = formatter.format(2500);
    System.out.println("Number with lading zeros: " + number);
  }
}





Format for GERMAN locale

   
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Locale locale = Locale.GERMAN;
    String string = NumberFormat.getNumberInstance(locale).format(-1234.56); 
    System.out.println(string);
  }
}
//-1.234,56





Format for the default locale

   
import java.text.NumberFormat;
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = NumberFormat.getNumberInstance().format(-1234.56);
    System.out.println(string);
  }
}
//-1,234.56





Formatting and Parsing a Locale-Specific Percentage

   
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Format
    Locale locale = Locale.CANADA;
    String string = NumberFormat.getPercentInstance(locale).format(123.45);
  }
}
// 12,345%





Formatting and Parsing a Number for a Locale

   

Format for CANADA locale
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Locale locale = Locale.CANADA;
    String string = NumberFormat.getNumberInstance(locale).format(-1234.56); 
    System.out.println(string);
  }
}
//-1,234.56





Formatting and Parsing Locale-Specific Currency

   
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Format
    Locale locale = Locale.GERMANY;
    String string = NumberFormat.getCurrencyInstance(locale).format(123.45);
  }
}
// 123,45 DM





Formatting a Number in Exponential Notation

   
The "E" symbol specifies that a number should be formatted in exponential notation. 
E symbol separates the mantissa from the exponent. 
E symbol must be followed by one or more "0" symbols. 
The number of "0" symbols specifies the minimum number of digits used to display the exponent.





left justification: left justify

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("|%-10.2f|", 123.123);
    System.out.println(fmt);
  }
}
//|123.12    |





left justification: Right justify by default

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("|%10.2f|", 123.123);
    System.out.println(fmt);
  }
}
//|    123.12|





NumberFormat and locale

   

import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] args) {
    double value = 1234567.89;
    System.out.println("Unformatted: " + value + "\n");
    Locale locales[] = { Locale.US, Locale.FRANCE, Locale.GERMANY, Locale.JAPAN,
        new Locale("fr", "FR", "EURO"), new Locale("de", "DE", "EURO") };
    for (int i = 0; i < locales.length; i++) {
      NumberFormat nf = NumberFormat.getCurrencyInstance(locales[i]);
      System.out.println("Formatted for " + locales[i] + ": " + nf.format(value));
    }
  }
}





Number Format by locale

     
import java.text.NumberFormat;
import java.util.Locale;
class NumberFormatApp {
  public static void main(String args[]) {
    NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
    String formattedCurrency = format.format(1000000);
    System.out.println(formattedCurrency);
  }
}





Number format viewer

    
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class NumberViewer extends JPanel {
  protected AbstractTableModel tableModel;
  protected double currentValue = 1234567.89d;
  protected final static Locale[] availableLocales;
  static {
    availableLocales = Locale.getAvailableLocales();
  }
  public final static int LOCALE_COLUMN = 0;
  public final static int NUMBER_COLUMN = 1;
  public final static int CURRENCY_COLUMN = 2;
  public final static int PERCENT_COLUMN = 3;
  public final static String[] columnHeaders = { "Locale", "Numeric", "Currency", "Percent" };
  public static void main(String[] args) {
    JFrame f = new JFrame("Number Viewer");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new NumberViewer());
    f.pack();
    f.setVisible(true);
  }
  public NumberViewer() {
    tableModel = new LocaleTableModel();
    JTable table = new JTable(tableModel);
    add(new JScrollPane(table));
  }
  class LocaleTableModel extends AbstractTableModel {
    public int getRowCount() {
      return availableLocales.length;
    }
    public int getColumnCount() {
      return columnHeaders.length;
    }
    public Object getValueAt(int row, int column) {
      Locale locale = availableLocales[row];
      NumberFormat formatter = NumberFormat.getNumberInstance();
      switch (column) {
      case LOCALE_COLUMN:
        return locale.getDisplayName();
      case NUMBER_COLUMN:
        formatter = NumberFormat.getNumberInstance(locale);
        break;
      case CURRENCY_COLUMN:
        formatter = NumberFormat.getCurrencyInstance(locale);
        break;
      case PERCENT_COLUMN:
        formatter = NumberFormat.getPercentInstance(locale);
        break;
      }
      return formatter.format(currentValue);
    }
    public String getColumnName(int column) {
      return columnHeaders[column];
    }
  }
}





NumberFormat with Constant Locale Usage

     
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class ConstantLocaleUsage {
  public static void main(String[] argv) {
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setParseIntegerOnly(false);
    double usersNumber;
    if (argv.length == 1)
      try {
        usersNumber = numberFormat.parse(argv[0]).doubleValue();
      } catch (ParseException e) {
        usersNumber = 197912.29;
      }
    else
      usersNumber = 1976.0826;
    numberFormat = NumberFormat.getNumberInstance(Locale.US);
    System.out.println("User"s number (US): "
        + numberFormat.format(usersNumber));
    numberFormat = NumberFormat.getNumberInstance(Locale.GERMANY);
    System.out.println("User"s number (GERMANY): "
        + numberFormat.format(usersNumber));
    numberFormat = NumberFormat.getNumberInstance();
    System.out.println("User"s number (DEFAULT LOCALE): "
        + numberFormat.format(usersNumber));
  }
}





Number Format with Locale

    
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.text.NumberFormat;
import java.util.Locale;
public class NumberFormatDemo {
  static public void displayNumber(Locale currentLocale) {
    Integer quantity = new Integer(123456);
    Double amount = new Double(345987.246);
    NumberFormat numberFormatter;
    String quantityOut;
    String amountOut;
    numberFormatter = NumberFormat.getNumberInstance(currentLocale);
    quantityOut = numberFormatter.format(quantity);
    amountOut = numberFormatter.format(amount);
    System.out.println(quantityOut + "   " + currentLocale.toString());
    System.out.println(amountOut + "   " + currentLocale.toString());
  }
  static public void displayCurrency(Locale currentLocale) {
    Double currency = new Double(9876543.21);
    NumberFormat currencyFormatter;
    String currencyOut;
    currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
    currencyOut = currencyFormatter.format(currency);
    System.out.println(currencyOut + "   " + currentLocale.toString());
  }
  static public void displayPercent(Locale currentLocale) {
    Double percent = new Double(0.75);
    NumberFormat percentFormatter;
    String percentOut;
    percentFormatter = NumberFormat.getPercentInstance(currentLocale);
    percentOut = percentFormatter.format(percent);
    System.out.println(percentOut + "   " + currentLocale.toString());
  }
  static public void main(String[] args) {
    Locale[] locales = { new Locale("fr", "FR"), new Locale("de", "DE"),
        new Locale("en", "US") };
    for (int i = 0; i < locales.length; i++) {
      System.out.println();
      displayNumber(locales[i]);
      displayCurrency(locales[i]);
      displayPercent(locales[i]);
    }
  }
}





Parse a GERMAN number

   
    
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Number number = NumberFormat.getNumberInstance(Locale.GERMAN).parse("-1.234,56");
    if (number instanceof Long) {
      System.out.println("Long value"); 
    } else {
      System.out.println("Double value"); 
    }
  }
}





Parse a number for a locale

   
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] args) throws Exception {
    Number number = NumberFormat.getNumberInstance(Locale.JAPAN).parse("25,000.75");
    if (number instanceof Long) {
      System.out.println("Long value: " + number.longValue());
    } else if (number instanceof Double) {
      System.out.println("Double value: " + number.doubleValue());
    }
  }
}





Parse a number with NumberFormat and Locale.CANADA

   
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Number number = NumberFormat.getPercentInstance(Locale.CANADA).parse("123.45%");
    // 1.2345
    if (number instanceof Long) {
      System.out.println("Long value");
    } else {
      System.out.println("Double value");
    }
  }
}





Parse number with NumberFormat and Locale

   
   
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
  public static void main(String[] argv) throws Exception {
    Number number = NumberFormat.getCurrencyInstance(Locale.GERMANY).parse("$123.45");
    if (number instanceof Long) {
      System.out.println("Long value");
    } else {
      System.out.println("Double value");
    }
  }
}





precision modifier: Display at most 15 characters in a string

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%.15s", "Formatting with Java is now easy.");
    System.out.println(fmt);
  }
}
//Formatting with





precision modifier: Format 4 decimal places

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%.4f", 123.1234567);
    System.out.println(fmt);
  }
}
//123.1235





precision modifier: Format to 2 decimal places in a 16 character field

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    // Format 4 decimal places.
    fmt = new Formatter();
    fmt.format("%16.2e", 123.1234567);
    System.out.println(fmt);
  }
}
//        1.23e+02





RoundingMode.CEILING

     
import java.math.RoundingMode;
import java.text.NumberFormat;
public class NumberFormatRounding {
  public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    nf.setRoundingMode (RoundingMode.CEILING);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();
  }
}





RoundingMode.FLOOR

     
import java.math.RoundingMode;
import java.text.NumberFormat;
public class NumberFormatRounding {
  public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    nf.setRoundingMode (RoundingMode.FLOOR);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();
  }
}





RoundingMode.HALF_DOWN

     
import java.math.RoundingMode;
import java.text.NumberFormat;
public class NumberFormatRounding {
  public static void main(String[] args) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    nf.setRoundingMode (RoundingMode.HALF_DOWN);
    System.out.println("Default rounding mode: " + nf.getRoundingMode());
    System.out.println("123.454 rounds to " + nf.format(123.454));
    System.out.println("123.455 rounds to " + nf.format(123.455));
    System.out.println("123.456 rounds to " + nf.format(123.456));
    System.out.println();
  }
}





The Format Specifiers

     
Format Specifier           Conversion Applied
%a                         Floating-point hexadecimal
%A
%b                         Boolean
%B
%c                         Character
%C
%d                         Decimal integer
%h                         Hash code of the argument
%H
%e                         Scientific notation
%E
%f                         Decimal floating-point
%g                         Uses %e or %f, whichever is shorter
%G
%o                         Octal integer
%n                         Inserts a newline character
%s                         String
%S
%t                         Time and date
%T
%x                         Integer hexadecimal
%X
%%                         Inserts a % sign





the NumberFormat object is created once when the program starts.

     
import java.text.NumberFormat;
public class MainClass {
  static NumberFormat cf = NumberFormat.getCurrencyInstance();
  public static void main(String[] args) {
    printMyAllowance();
    printCostOfPaintBallGun();
  }
  public static void printMyAllowance() {
    double myAllowance = 5.00;
    cf = NumberFormat.getCurrencyInstance();
    System.out.println("My allowance: " + cf.format(myAllowance));
  }
  public static void printCostOfPaintBallGun() {
    double costOfPaintBallGun = 69.95;
    cf = NumberFormat.getCurrencyInstance();
    System.out.println("Cost of Paint Ball Gun: " + cf.format(costOfPaintBallGun));
  }
}





The Uppercase Option

     
Specifier            Effect
%A                   Causes the hexadecimal digits a through f to be displayed in uppercase as A through F. Also, the prefix 0x is displayed as 0X, and the p will be displayed as P.
%B                   Uppercases the values true and false.
%C                   Uppercases the corresponding character argument.
%E                   Causes the e symbol that indicates the exponent to be displayed in uppercase.
%G                   Causes the e symbol that indicates the exponent to be displayed in uppercase.
%H                   Causes the hexadecimal digits a through f to be displayed in uppercase as A through F.
%S                   Uppercases the corresponding string.
%T                   Causes all alphabetical output to be displayed in uppercase.
%X                   Causes the hexadecimal digits a through f to be displayed in uppercase as A through F. Also, the optional prefix 0x is displayed as 0X, if present.





Use grouping to display a number

   
import java.text.NumberFormat;
public class Main {
  public static void main(String args[]) {
    NumberFormat nf = NumberFormat.getInstance();
    System.out.println("Default format: " + nf.format(1234567.678));
    nf.setGroupingUsed(false);
    System.out.println("Format without groupings: " + nf.format(1234567.678));
  }
}
/*
Default format: 1,234,567.678
Format without groupings: 1234567.678
*/





Using an Argument Index

     
import java.util.Formatter;
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%3$d %1$d %2$d", 10, 20, 30);
    System.out.println(fmt);
  }
}
//30 10 20





Using only 0"s to the left of E forces no decimal point

   
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
  public static void main(String[] argv) throws Exception {
    NumberFormat formatter = new DecimalFormat("0E0");
    String s = formatter.format(-1234.567);
    System.out.println(s);
  }
}
// -1E3





Using the Format Flags

     
Flag            Effect
-               Left justification
#               Alternate conversion format
0               Output is padded with zeros rather than spaces
space           Positive numeric output is preceded by a space
+               Positive numeric output is preceded by a + sign
,               Numeric values include grouping separators
(               Negative numeric values are enclosed within parentheses