aspose file tools*
The moose likes Beginning Java and the fly likes Number Format Specifiers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Number Format Specifiers" Watch "Number Format Specifiers" New topic
Author

Number Format Specifiers

V Bose
Ranch Hand

Joined: Jul 10, 2003
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

Joined: Nov 09, 2000
Posts: 6450
Check out the DecimalFormat and NumberFormat classes.
Herb Schildt
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
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 ]

For my latest books on Java, including my Java Programming Cookbook, see HerbSchildt.com
Sawyer Shillong
Greenhorn

Joined: Nov 07, 2001
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

Joined: Oct 01, 2003
Posts: 239
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Number Format Specifiers