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?
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. NumberFormat helps you to format and parse numbers for any locale.
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.
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.
If you want to set manually the number of decimal places use one of the following options:
Firstly:
//sets 'd' to 3 decimal places & then assigns it to 'formattedNum'
String formattedNum = String.format("%.3f", d); //variable 'd' taken from your code above
OR
//declares an object of 'DecimalFormat'
DecimalFormat aDF = new DecimalFormat("#.000");
//formats value stored in 'd' to three decimal places
String fomrattedNumber = aDF.format(d);
In my opinion the second option suits best for your case.
The number created from parsed String has more fractional digits. But when you try to output it uses format's MaximumFractionDigits
to create String from any given Number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With