• Post Reply Bookmark Topic Watch Topic
  • New Topic

Rounding a double  RSS feed

 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What is the standard way to round a double at a precision of x? I know there is a way when you multiply your double with a power of 10, then do a cast to int and then divide with the same power of 10.
Con of this method: when your double is bigger than the maximum value for integer, you will get always the maximum integer value, so that isn't a really good work around.
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apply the algorithm only to the fractional portion of the double to avoid the loss of precision.

Cheers
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tom Blough:
Apply the algorithm only to the fractional portion of the double to avoid the loss of precision.

Cheers


Same problem if fractional portion is to big to fit in the int-datatype
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See if BigDecimal.round() does what you need. And remember floating types only approximate decimal amounts. For money or other critical decimal math you'll probably be happier with integral types or BigDecimal.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!