Skip to main content
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

How to round a number to n decimal places in Java

What I would 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 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.

I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.

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

String.format("%.5g%n", 0.912385);

returns:

0.91239

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

String.format("%.5g%n", 0.912300);

returns:

0.91230

Another method is to use the DecimalFormatter:

DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);

returns:

0.91238

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:

0.912385 -> 0.91239
0.912300 -> 0.9123

What is the best way to achieve this in Java?

Answer*

Cancel
5
  • 27
    I believe one of the goals of the question was that "there should not be any trailing zeroes".
    Lunchbox
    –  Lunchbox
    2012-11-20 20:10:16 +00:00
    Commented Nov 20, 2012 at 20:10
  • 9
    For this question, the op didn't want zeros, but this is exactly what I wanted. If you have a list of numbers with 3 decimal places, you want them to all have the same digits even if it's 0.
    Tom Kincaid
    –  Tom Kincaid
    2014-04-08 17:06:39 +00:00
    Commented Apr 8, 2014 at 17:06
  • You forgot to specify RoundingMode.
    IgorGanapolsky
    –  IgorGanapolsky
    2015-09-29 21:27:08 +00:00
    Commented Sep 29, 2015 at 21:27
  • 2
    @IgorGanapolsky by default Decimal mode uses RoundingMode.HALF_EVEN.
    EndermanAPM
    –  EndermanAPM
    2016-09-27 15:40:01 +00:00
    Commented Sep 27, 2016 at 15:40
  • Or this (no check with instanceof etc). First create a suitable DecimalFormat. DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(); then you can specify grouping and pattern. Try df.toPattern(); and df.applyPattern("#,##0.00000;(#)"); and then you can use df.parse(String); and ` df.format(double);` do format after the pattern. This case negative numbers will be within parenthesis.
    Anders
    –  Anders
    2024-10-30 18:56:49 +00:00
    Commented Oct 30, 2024 at 18:56

Morty Proxy This is a proxified and sanitized view of the page, visit original site.