By dave | July 1, 2012

java.text.NumberFormat is the class used to convert numeric values such as int, long and double into Strings.

It has been around since the early days of Java, and generally performs well. Especially if you cache an instance of the class for repeated use. IMHO the only down side to using NumberFormat is that it can look a little verbose.

To get hold of a copy of the NumberFormat class, call one of the static factory methods on the NumberFormat object:

  • getNumberInstance()
  • getIntegerInstance()
  • getCurrencyInstance()
  • getPercentInstance()
  • getInstance()

Each of the various factory methods provides a number formatter ready to provide a textual representation for a given case. For example the integer instance will format ignoring any fractional decimal part.

NumberFormat can also be configured manually with appropriate settings, as follows in this example:

package com.thecoderscorner.example;

import java.text.NumberFormat;

public class Formatting
    public static void main(String[] args)
        // we create a number formatter for integers with no grouping
        int integerVal = 100;
        NumberFormat fmt = NumberFormat.getInstance();
        fmt.setGroupingUsed(false); // dont want to group 1,000's
        fmt.setMaximumFractionDigits(0); // no fractions - integer only
        fmt.setMinimumFractionDigits(0); // as above
        String output = fmt.format(integerVal);

        // and now for a double with grouping and 3dp.
        double floatingValue = 100023049.39434;
        fmt = NumberFormat.getInstance();
        fmt.setGroupingUsed(true); // we need it printable
        fmt.setMaximumFractionDigits(3); // 3 dp floating
        fmt.setMinimumFractionDigits(3); // as above
        output = fmt.format(floatingValue);

        // and here's an example using printf.. %d prints an integer, %.3f
        // is a float to 3dp of precision.
        System.out.printf("%d, %.3f", integerVal, floatingValue);

and the output was

100, 100023049.394
Process finished with exit code 0

Other pages within this category

comments powered by Disqus

This site uses cookies to analyse traffic, serve ads by Google AdSense (non-personalized in EEA/UK), and to record consent. We also embed Twitter, Youtube and Disqus content on some pages, these companies have their own privacy policies.

Our privacy policy applies to all pages on our site

Should you need further guidance on how to proceed: External link for information about cookie management.