I am trying out the methods and the functionality of the class NumberFormat
and I have reached to a strange result. I compile and run the following program:
public static void main(String[] args) {
Locale loc = Locale.US;
NumberFormat nf = NumberFormat.getInstance(loc);
System.out.println("Max: "+nf.getMaximumFractionDigits());
System.out.println("Min: "+nf.getMinimumFractionDigits());
try {
Number d = nf.parse("4527.9997539");
System.out.println(d);
// nf.setMaximumFractionDigits(4);
System.out.println(nf.format(4527.999753));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The output is:
Max: 3
Min: 0
4527.9997539
4,528
That means that it does not take into account any fraction digit. If I uncomment the line:
nf.setMaximumFractionDigits(4);
the output is:
Max: 3
Min: 0
4527.9997539
4,527.9998
In other words it works OK. What is actually happening with method setMaximumFractionDigits()
and it does not bring the number containing 3 fraction digits in the first case?
I found the answer finally. The method setMaximumFractionDigits()
has an effect only on the method format()
. It has nothing to do with parse()
. In my code fragment I use the method format()
after setting manually the number of fraction digits to 4, consequently it affects the result.