Wednesday, March 4, 2009

Number Format class

Before Going to learn about Number Format Batter know about Locale Class

Number Format:
By using number format object we can represent the number specific to a particular region (a particular locale).This class present in java .text package.It is an abstract class we are not allowed to create object by using constractor.
i.e NumberFormat nf=new NumberFormat() -----> not valid

Getting NumberFormat object for defaultLocale using factory method:
static NumberFormat getInstance();
static NumberFormat getNumberInstance();
static NumberFormat getCurrrencyInstance();
static NumberFormat getPercentInstance();
return NumberFormat object for representing currency and percentage.

Getting NumberFormat object for a particular Locale:
static NumberFormat getInstance(Locale l);
static NumberFormat getNumberInstance(Locale l);
static NumberFormat getCurrencyInstance(Locale l);
static NumberFormat getPercentInstance(Locale l);

Methods of the NumberFormat class:
String format (long l);
String format(double d);
Number parse(String s)throws parseException ---->This method is for converting locale specific to java number form.It throws a checked exception parseException.

Example to Display the currency value 1234.343 for locations India .Italy and us:
Import java.text.NumberFormat;
Import java.util.*;
Class NFDemo
{
Public staic void main(String arg[])
{
double d=123456.789;
Locale India=new Locale(“pa”,”IN”);
NumberFormat nf=NumberFormat.getCurrencyInstance(India);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
NumberFormat nf=NumberFormat.getCurrencyInstance(locale.ITALY);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
NumberFormat nf=NumberFormat.getCurrencyInstance(locale.UNITEDSTATES);
String s=nf.format(d);
Systm.out.println(“india notation is:”+s);
}
}
}
output:
INR123,456.789
C1 123.456.789
$123,456.789
we can set the maximam and minimum number of digits for integer and fractional parts.For this we can use the following methods of NumberFormat class.
public void setMaximumFractionalDigits(int n);
public void setMinimumFractionalDigits(int n);
public void setMaximumIntegerDigits(int n);
public void setMinimumIntegerDigits(int n);

Example:
Import java.text.*;
Import java.util.*;
Class NFDemo
{
public static vopid main(String arg[])
{
double d=123.456;
NumberFormat nf=NumberFormat.getInstance();

Systm.out.println(nf.format(d)); //123.456
nf. setMaximumFractionalDigits(2);
System.out.println(nf.format(d)); //123.46

nf.setMinimumFractionalDigits(5);
System.out.println(nf.format(d)); //123.45600
nf.setMaximumIntegerDigits(2);
System.out.println(nf.format(d)); //23.456
The most significant bits will be lost
nf.setMinimumIntegerDigits(6);
System.out.println(nf.format(d)); //000123.456
}
}

0 comments:

Post a Comment