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? Dec 22, 2020 in Java 493 views

## 1 answer to this question.

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

Example:

```DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}
```

gives the output:

```12
123.1235
0.23
0.1
2341234.2125``` answered Dec 22, 2020 by
• 65,970 points

## How to round any number to n decimal places in Java?

new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP); will get you a BigDecimal. To ...READ MORE

## How to round a double to 2 decimal places?

double value = 200.3456; System.out.printf("Value: %.2f", value); You can ...READ MORE

## How to round up a value to 2 decimal places?

double d = 2.34568; DecimalFormat f = new ...READ MORE

## How can I convert a String variable to a primitive int in Java

Here are two ways illustrating this: Integer x ...READ MORE

## How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

+1 vote

## How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

## What are the differences between getText() and getAttribute() functions in Selenium WebDriver?

See, both are used to retrieve something ...READ MORE