• 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

Double precision

 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the best way to limit a Double objects precision. For example I want the Double object to be limited to only 2 decimal places. Below are examples of what I need and what I don't need.

Example:

Good: 49.99
Bad 49.9982939372

Thanks for any help.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you create a BigDecimal object from your double value, then you can set the scale (2) and choose your rounding method (looks like you want ROUND_DOWN or ROUND_FLOOR). After that, you can return to a type double if you like. This might be all you need, but suppose the result is 49.9 and you want to display a zero in that second decimal place. This is where DecimalFormat comes in...


NOTE: When you make your BigDecimal object, you'll probably want to use the constructor that takes a String argument rather than a double. See API.

Ref:
http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html
http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html
[ September 24, 2004: Message edited by: marc weber ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic