Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

rounding a double value

 
Alex Dubin
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a double value (1.63722333) and I need to round it to the nearest tenth so I get 1.64. How can I do this?

thanks,
Alex
 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Alex


Cheers
 
Alex Dubin
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cool, thanks!
 
Tom McC
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to clarify, Math.round() will always round to the nearest whole number. The reason Kundret's code rounds to the nearest hundredth is because we FIRST multiply it by 100, then, after rounding it, divide by 100 again. This way, you can round to any place, as long as you move the decimal point (by multiplying/dividing) before and after the rounding.
 
Andrew Morris
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another alternate to round a double value, make a java.text.DecimalFormat like:
static DecimalFormat df=new DecimalFormat("0.00");
use
System.out.println(df.format(aDoubleValue));
and it does the rounding.

-----------------
Andrew Morris
www.devsquare.com
DevSquare - Online Application Development
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic