# Number Format Specifiers

V Bose
Ranch Hand
Posts: 113
Is there a way I can specify number formatting in Java.
Lets say I have a double 0.0000045
Can I force it to use(or not to use) E notation when used with a println.
Or with a number like 12.00000000000 can I specify how many decimal places to 'println' ?

Jason Menard
Sheriff
Posts: 6450
Check out the DecimalFormat and NumberFormat classes.

Herb Schildt
Author
Ranch Hand
Posts: 253
6
As Jason suggests, you will want to explore the classes in the package java.text, such as NumberFormat. Using NumberFormat you can bypass the default toString conversions. For example, you can specify the minimum number of fractional digits, among other things. Here is short example,

The output is shown here:
Default output: 1.23456789123E11
Formatted output: 123,456,789,123.000000000000
[ October 07, 2003: Message edited by: Herb Schildt ]

Sawyer Shillong
Greenhorn
Posts: 9
I am confused by NumberFormat,
NumberFormat nf=NumberFormat.getInstance();
nf.setMaximumFractionDigits(6);
nf.setMinimumFractionDigits(2);
System.out.println("2.1242326 result==>"+nf.format(4.1234515)); //4.123452
System.out.println("2.1242326 result==>"+nf.format(4.1234525));//4.123452
System.out.println("2.1247326 result==>" +nf.format(4.1234535));//4.123454
Why the second statement return 4.123452,not 4.123453.

Herb Schildt
Author
Ranch Hand
Posts: 253
6
You ask "Why the second statement return 4.123452,not 4.123453?"
The value that you are formatting to 6 fractional digits is 4.1234525. Thus, the 7th fractional digit is a 5. This causes the output to be rounded to 4.123452. Here is why.
In general, when a number ends in 5, that number can just as properly be rounded up as it can be rounded down. However, in this case, it is common practice to round the number to an even value. This is what is occuring here. Thus, the output that you see is the result of 4.1234525 is being rounded to an even number that has 6 fractional digits.