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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Rounding a double

Sheriff
Posts: 11338
177
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.

Ranch Hand
Posts: 263
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

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

(instanceof Sidekick)
Ranch Hand
Posts: 8791
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.