Round a double to 2 decimal places

Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places. For example: Original version; watch out with this This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out. I’ve been using the above to round … Read more

Round a double to 2 decimal places [duplicate]

Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places. For example: Original version; watch out with this This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out. I’ve been using the above to round … Read more

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining. Here are the docs from Math.round(double): … Read more