Tuesday, April 13, 2010

Formatting(Precision) Java Double /Float Decimal Digits

Formatting( Precision ) Java Double Decimal Digits

Formatters converts a floating point/double value  to a string  with a specified number  of decimals.

For formatting the decimal part of double/Float we can use NumberFormat or DecimalFormat .

The difference between them is that
        NumberFormat is an abstract class.
        DecimalFormat is a concrete implementation of NumberFormat.

Using NumberFormat:

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are.
Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally. 

    NumberFormat nfrmtr = NumberFormat.getNumberInstance();
    nfrmtr.setGroupingUsed(false);
    nfrmtr.setMaximumFractionDigits(2);
    nfrmtr.setMinimumFractionDigits(2);
    double dval = 0.0;
    System.out.println(nfrmtr.format(dval));

Using DecimalFormat:

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized. 

As DecimalFormat is implementing NumberFormat Class we can use the functions available in NumberFormat.

    DecimalFormat dfrmtr = new DecimalFormat("###.##");
    double dval = 0.0;
    System.out.println(dfrmtr.format(dval));     

Sample Program :

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class DecimalFormatter {
    public static void main(String srgs[]){
   
        DecimalFormat dfrmtr = new DecimalFormat("###.##");

        NumberFormat nfrmtr = NumberFormat.getNumberInstance();
        nfrmtr.setGroupingUsed(false);
        nfrmtr.setMaximumFractionDigits(2);
        dfrmtr.setMinimumFractionDigits(2);
       
        double dval = 0.0;
        for (int i = 0; i < 10; i++)
        {
            dval += 0.111;
            System.out.println(dval+" "+dfrmtr.format(dval)+"  "+nfrmtr.format(dval));           
        }
    }
}

Source NumberFormat
Source DecimalFormat