Explain Codes LogoExplain Codes Logo

Round up to 2 decimal places in Java?

java
rounding
bigdecimal
precision
Nikita BarsukovbyNikita Barsukov·Mar 5, 2025
TLDR

To round up to 2 decimal places in Java, use BigDecimal with RoundingMode.UP. It offers precision that floating point arithmetic sorely lacks:

BigDecimal rounded = new BigDecimal("3.14159").setScale(2, RoundingMode.UP); System.out.println(rounded); // "3.15". Math teachers hate this.

With BigDecimal, you're ensuring that rounding happens regardless of the third decimal digit.

Understand the power of BigDecimal

Precision is crucial in programming. Working with BigDecimal, you prevent the sneaky troubles of floating-point arithmetic:

  • Double Trouble?: Doubles boast of massive range, but often compromise on precision after arithmetic operations. Taking care of PRECISE rounding? Give doubles a miss.
  • String theory revisited: Initializing BigDecimal with a string representation of the number prevents those annoying pesky rounding errors that occur due to binary representation of floating-point numbers.

Mastering the use of BigDecimal

BigDecimal value = new BigDecimal("123.13698"); BigDecimal rounded = value.setScale(2, RoundingMode.HALF_EVEN); System.out.println(rounded); // "123.14". Don't you love it when numbers obey you?
  • Decoding setScale(): Helps define the scale - how many digits do you need to the right of the decimal point.
  • RoundingMode.HALF_EVEN: Think of it as that indecisive friend who finally sides with the closest even number when the number is equidistant from two neighbors.

Looking at alternatives

Keep it simple with Math.round()

If rounding seems trivial to you:

double result = (double) Math.round(value * 100) / 100;

In Math we trust.

The cereal box decoder - DecimalFormat class

When you need to format and round numbers:

DecimalFormat df = new DecimalFormat("0.00"); String formatted = df.format(2.3456); System.out.println(formatted); // "2.35". That's a trim figure. double backToDouble = Double.parseDouble(formatted);
  • Patterns rule: Use "0.00" to ensure two decimal places and let the system handle the rounding.
  • No more leading zeros: "##.00" gives you two decimals without the leading zeros.
  • Maintain consistency: Casting to double to ensure type consistency.

String formatting

For a quick display, simply use String.format():

System.out.println(String.format("%.2f", 2.3456)); // "2.35". As elegant as a ballet dancer's pirouette.

Edge cases and rendering nuances

println() can trick you!

System.out.println(value) might give you a.rounded-looking number, but it's not the real value. Slick as a con-artist.

Getting back to reality after DecimalFormat

Number backToNumber = df.parse(formatted);
  • Beware: Parsing back to a number type can reintroduce all the old chaos of floating-point inaccuracies. Ah, the circle of life!

BigDecimal vs. DecimalFormat

So, which one to choose?

  • Precise calculations: Choose BigDecimal. It's a no-brainer.
  • Formatting for a glance: DecimalFormat will do the job.

Remember the memory!

BigDecimal is a memory hogger when compared to primitives like double. Balance performance and precision when designing your system.