# How to round a number to 2 decimal spaces (java)?

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:

````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?

Replay

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
12341234.2125
```
```

Assuming `value` is a `double`, you can do:

``````(double)Math.round(value * 100000d) / 100000d
```
```

That's for 5 digits precision. The number of zeros indicate the number of decimals.

``````new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP);
```
```

will get you a `BigDecimal`. To get the string out of it, just call that `BigDecimal`'s `toString` method, or the `toPlainString` method for Java 5+ for a plain format string.

You can also use the

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

to make sure you have the trailing 0's.

As some others have noted, the correct answer is to use either `DecimalFormat` or `BigDecimal`. Floating-point doesn't have decimal places so you cannot possibly round/truncate to a specific number of them in the first place. You have to work in a decimal radix, and that is what those two classes do.

I am posting the following code as a counter-example to all the answers in this thread and indeed all over StackOverflow (and elsewhere) that recommend multiplication followed by truncation followed by division. It is incumbent on advocates of this technique to explain why the following code produces the wrong output in over 92% of cases.

``````public class RoundingCounterExample
{

static float roundOff(float x, int position)
{
float a = x;
double temp = Math.pow(10.0, position);
a *= temp;
a = Math.round(a);
return (a / (float)temp);
}

public static void main(String[] args)
{
float a = roundOff(0.0009434f,3);
System.out.println("a="+a+" (a % .001)="+(a % 0.001));
int count = 0, errors = 0;
for (double x = 0.0; x < 1; x += 0.0001)
{
count++;
double d = x;
int scale = 2;
double factor = Math.pow(10, scale);
d = Math.round(d * factor) / factor;
if ((d % 0.01) != 0.0)
{
System.out.println(d + " " + (d % 0.01));
errors++;
}
}
System.out.println(count + " trials " + errors + " errors");
}
}
```
```

Output of this program:

``````10001 trials 9251 errors
```
```

EDIT: I note that this post has been here for nearly six months and no explanations have been forthcoming. Draw your own conclusions.

Suppose you have

``````double d = 9232.129394d;
```
```

you can use `BigDecimal`

``````BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);
d = bd.doubleValue();
```
```

or without BigDecimal

``````d = Math.round(d*100)/100.0d;
```
```

with both solutions `d == 9232.13`

You can use the DecimalFormat class.

``````double d = 3.76628729;

DecimalFormat newFormat = new DecimalFormat("#.##");
double twoDecimal =  Double.valueOf(newFormat.format(d));
```
```

Real's Java How-to posts this solution, which is also compatible for versions before Java 1.6.

``````BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
```
```
``````double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;
```
```

@Milhous: the decimal format for rounding is excellent:

You can also use the

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

to make sure you have the trailing 0's.

I would add that this method is very good at providing an actual numeric, rounding mechanism - not only visually, but also when processing.

Hypothetical: you have to implement a rounding mechanism into a GUI program. To alter the accuracy / precision of a result output simply change the caret format (i.e. within the brackets). So that:

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

would return as output: `0.912385`

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

would return as output: `0.91239`

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

would return as output: `0.9124`

[EDIT: also if the caret format is like so ("#0.############") and you enter a decimal, e.g. 3.1415926, for argument's sake, DecimalFormat does not produce any garbage (e.g. trailing zeroes) and will return: `3.1415926` .. if you're that way inclined. Granted, it's a little verbose for the liking of some dev's - but hey, it's got a low memory footprint during processing and is very easy to implement.]

So essentially, the beauty of DecimalFormat is that it simultaneously handles the string appearance - as well as the level of rounding precision set. Ergo: you get two benefits for the price of one code implementation. ;)

You could use the following utility method-

``````public static double round(double valueToRound, int numberOfDecimalPlaces)
{
double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);
double interestedInZeroDPs = valueToRound * multipicationFactor;
return Math.round(interestedInZeroDPs) / multipicationFactor;
}
```
```

You can use BigDecimal

``````BigDecimal value = new BigDecimal("2.3");
value = value.setScale(0, RoundingMode.UP);
BigDecimal value1 = new BigDecimal("-2.3");
value1 = value1.setScale(0, RoundingMode.UP);
System.out.println(value + "n" + value1);
```
```

Try this: org.apache.commons.math3.util.Precision.round(double x, int scale)

Apache Commons Mathematics Library homepage is: http://commons.apache.org/proper/commons-math/index.html

The internal implemetation of this method is:

``````public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}

public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
```
```

Here is a summary of what you can use if you want the result as String:

1. DecimalFormat#setRoundingMode():
``````DecimalFormat df = new DecimalFormat("#.#####");
df.setRoundingMode(RoundingMode.HALF_UP);
String str1 = df.format(0.912385)); // 0.91239
```
```
2. BigDecimal#setScale()
``````String str2 = new BigDecimal(0.912385)
.setScale(5, BigDecimal.ROUND_HALF_UP)
.toString();
```
```

Here is a suggestion of what libraries you can use if you want `double` as a result. I wouldn't recommend it for string conversion, though, as double may not be able to represent what you want exactly (see e.g. here):

1. Precision from Apache Commons Math
``````double rounded = Precision.round(0.912385, 5, BigDecimal.ROUND_HALF_UP);
```
```
2. Functions from Colt
``````double rounded = Functions.round(0.00001).apply(0.912385)
```
```
3. Utils from Weka
``````double rounded = Utils.roundDouble(0.912385, 5)
```
```

If you really want decimal numbers for calculation (and not only for output), do not use a binary-based floating point format like double. Use BigDecimal or any other decimal-based format. – Paŭlo Ebermann

I do use BigDecimal for calculations, but bear in mind it is dependent on the size of numbers you're dealing with. In most my implementations, i find parsing from double or integer to Long is sufficient enough for very large number calculations. In fact, i've recently used parsed-to-Long to get accurate representations (as opposed to hex results) in a gui for numbers as big as ################################# characters (as an example).

The code snippet below shows how to display n digits. The trick is to set variable pp to 1 followed by n zeros. In the example below, variable pp value has 5 zeros, so 5 digits will be displayed.

``````double pp = 10000;

double myVal = 22.268699999999967;
String needVal = "22.2687";

double i = (5.0/pp);

String format = "%10.4f";
String getVal = String.format(format,(Math.round((myVal +i)*pp)/pp)-i).trim();
```
```

If you're using `DecimalFormat` to convert `double` to `String`, it's very straightforward:

``````DecimalFormat formatter = new DecimalFormat("0.0##");
formatter.setRoundingMode(RoundingMode.HALF_UP);

double num = 1.234567;
return formatter.format(num);
```
```

There are several `RoundingMode` enum values to select from, depending upon the behaviour you require.

I agree with the chosen answer to use `DecimalFormat` --- or alternatively `BigDecimal`.

However if you do want to round the double value and get a `double` value result, you can use `org.apache.commons.math3.util.Precision.round(..)` as mentioned above. The implementation uses `BigDecimal`, is slow and creates garbage.

A similar but fast and garbage-free method is provided by the `DoubleRounder` utility in the decimal4j library:

`````` double a = DoubleRounder.round(2.0/3.0, 3);
double b = DoubleRounder.round(2.0/3.0, 3, RoundingMode.DOWN);
double c = DoubleRounder.round(1000.0d, 17);
double d = DoubleRounder.round(90080070060.1d, 9);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
```
```

Will output

`````` 0.667
0.666
1000.0
9.00800700601E10
```
```

Disclaimer: I am involved in the decimal4j project.

Where dp = decimal place you want, and value is a double.

``````    double p = Math.pow(10d, dp);

double result = Math.round(value * p)/p;
```
```
Category: java Time: 2008-09-30 Views: 2