Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
cake naiyou
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 207
Eclipse IDE Firefox Browser jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There can be many ways of doing this.

One of them is using DecimalFormat class:


 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Riaan Nel
Ranch Hand
Posts: 160
IntelliJ IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49411
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For displaying the number, it is far easier to use the %f tag. Details in the Java™ Tutorials and in the Formatter class documentation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic