Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Round a double to 2 places of Decimal  RSS feed

 
Angela lewis
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a double value which is multiplied by another value. I want that the result be in only 2 places of decimal rather than the unnecessary precision i am getting.
please suggest.
 
Ali Gohar
Ranch Hand
Posts: 572
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use java.text.NumberFormat class to do so.
You can find the help regarding that from :
http://java.sun.com/j2se/1.4.2/docs/api/java/text/NumberFormat.html
 
Rikko Verrijzer
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Perhaps the most simple, but not very subtle solution would be: multiply by 100, call Math.round(double), cast to double and divide by 100.
long story short, something like this:
roundeDoubleValue = (double)Math.round(someDoubleValue*100)/100;
But there might be a better solution though
Rikko
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!