Round a double to 2 decimal places
To quickly round a double to 2 decimal places, use BigDecimal
with setScale(2, RoundingMode.HALF_UP)
. This is how it's done in Java:
This line of code rounds valueToBeRounded
to exactly 123.46 and it's ready-to-go!
Why 'BigDecimal' is better for precise rounding
When it comes to precision in rounding off values, BigDecimal
is Java's magic wand. This is how it's done:
Using the String
constructor is a useful trick here. It maintains perfect precision, a feature that doubles often lack.
Be aware of the deceptive double
In Java, double
and float
types can be quite deceptive. They'll lead you to believe you're dealing with precise values, but they're subject to rounding errors. If you're dealing with financial calculations or other precision-sensitive use-cases, these types are not your friends.
The alternative: Mighty Math.round method
When precision is not the topmost priority, Java's built-in Math.round()
function can come to your rescue. Here's how it works:
Formatting rounded double: A step further
Let's say you've achieved a perfect round off to two decimal places, but want to make it look good on the output screen.
Befriend 'DecimalFormat'
This DecimalFormat function is purely cosmetic but sometimes, appearances matter. So, use it as you please.
Direct-Print Method System.out.printf()
String-getting Method String.format()
These methods are essentially beauty hacks for your rounded figures. They might not increase precision but definitely improve presentation.
Staying safe against exceptions
With great math operations, come great exceptions:
Avoid overflows with large doubles
Always validate your inputs and be aware of their range.
Don't let illegal arguments spoil the party
Negative decimals in rounding methods? They're party spoilers.
A smoothing function wouldn't decrease the roughness, and a rounding function wouldn't unround the numbers.
Use the 'Apache Common Math's Precision' when precision is crucial
It's a trusted method for scientific computations, and handles rounding remarkably well.
Was this article helpful?