• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 207
jQuery Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There can be many ways of doing this.

One of them is using DecimalFormat class:


 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Ranch Hand
Posts: 160
IntelliJ IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic