Explain Codes LogoExplain Codes Logo

Round a double to 2 decimal places

java
rounding
precision
math
Nikita BarsukovbyNikita Barsukov·Sep 26, 2024
TLDR

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:

double valueToBeRounded = 123.456789; double accuratelyRounded = BigDecimal .valueOf(valueToBeRounded) .setScale(2, RoundingMode.HALF_UP) .doubleValue(); // Prints: "Hey look, 123.456789 just turned into 123.46. Magic, eh?" System.out.println("Hey look, "+ valueToBeRounded +" just turned into "+ accuratelyRounded +". Magic, eh?");

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:

double value = 123.456789; BigDecimal roundedValue = new BigDecimal(String.valueOf(value)) .setScale(2, RoundingMode.HALF_UP); // Prints: "123.456789 is now a well-rounded 123.46. Achievement unlocked." System.out.println(value + " is now a well-rounded " + roundedValue + ". Achievement unlocked.");

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:

double quickRoundingResult = Math.round(value * 100.0) / 100.0; // Prints: "123.456789 just got a quick makeover to 123.46. No biggie." System.out.println(value + " just got a quick makeover to " + quickRoundingResult + ". No biggie.");

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'

DecimalFormat df = new DecimalFormat("0.00"); String fashionablyRounded = df.format(value); // Prints: "123.46 is now runway ready as 123.46. Who knew numbers could be so chic?" System.out.println(value + " is now runway ready as " + fashionablyRounded + ". Who knew numbers could be so chic?");

This DecimalFormat function is purely cosmetic but sometimes, appearances matter. So, use it as you please.

Direct-Print Method System.out.printf()

System.out.printf("%.2f", value);

String-getting Method String.format()

String anotherFashionablyRounded = String.format("%.2f", value);

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

// The bad code: Double value is too large to handle. double wayTooLarge = Math.round(Double.MAX_VALUE * 100.0) / 100.0; // This will give you grief.

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.

// The bad code: Illegal Argument exception alert! BigDecimal badValue = new BigDecimal("123.456").setScale(-2, RoundingMode.HALF_UP); // This is just wrong.

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

double superPreciseRounded = Precision.round(value, 2);

It's a trusted method for scientific computations, and handles rounding remarkably well.