File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to save the double value in a customized format, such as keeping 6 digits only Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to save the double value in a customized format, such as keeping 6 digits only" Watch "How to save the double value in a customized format, such as keeping 6 digits only" New topic
Author

How to save the double value in a customized format, such as keeping 6 digits only

cake naiyou
Greenhorn

Joined: Apr 29, 2011
Posts: 27
In my code, the computation can generate double value in its standard long format, like 0.469696968793869

If I just want to save it in a shorter format with just six digits, like 0.469697, and use it for later computation. How to do that? Thanks.
Piyush Joshi
Ranch Hand

Joined: Jun 10, 2011
Posts: 207

There can be many ways of doing this.

One of them is using DecimalFormat class:



Piyush
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

Not really. This still has the problem that double and float are not precise; see item 20 in our Beginner's FAQ. The only data type in the Java API that can solve this issue is BigDecimal. Never instantiate one from a double though, use the String constructor instead:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Riaan Nel
Ranch Hand

Joined: Apr 23, 2009
Posts: 157

If the format is only relevant when displaying the data, use DecimalFormat to get a formatted String representation of the double. The double value is just a number - it doesn't have a strict 'format' as such. As an example, 1.000000 and 1.0 are the exact same number.

If precision is important, use a BigDecimal instead of a double.


"The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man." - George Bernard Shaw
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
For displaying the number, it is far easier to use the %f tag. Details in the Java™ Tutorials and in the Formatter class documentation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to save the double value in a customized format, such as keeping 6 digits only