How to round a number to n decimal places in Java

Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.

gives the output:

What I’d like is a method to convert a double to a string which rounds using the half-up method. I.e. if the decimal to be rounded is a 5, it always rounds up the previous number. This is the standard method of rounding most people expect in most situations.

I also would like only significant digits to be displayed. That is there should not be any trailing zeroes.

I know one method of doing this is to use the String.format method:


which is great, however it always displays numbers with 5 decimal places even if they are not significant:


Another method is to use the DecimalFormatter:


However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I’d like is this:

4.5/5 - (2 votes)