Home » Java » Round a double to 2 decimal places [duplicate]

# Round a double to 2 decimal places [duplicate]

Questions:

Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places.

For example:

``````round(200.3456, 2); // returns 200.35
``````

# Original version; watch out with this

``````public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();

long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
``````

This breaks down badly in corner cases with either a very high number of decimal places (e.g. `round(1000.0d, 17)`) or large integer part (e.g. `round(90080070060.1d, 9)`). Thanks to Sloin for pointing this out.

I’ve been using the above to round “not-too-big” doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it’s best to avoid it, since more reliable ways are readily available, with cleaner code too.

(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)

``````public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();

BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
``````

Note that `HALF_UP` is the rounding mode “commonly taught at school”. Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.

Of course, if you prefer, you can inline the above into a one-liner:
`new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()`

# And in every case

Always remember that floating point representations using `float` and `double` are inexact.
For example, consider these expressions:

``````999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
``````

For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:

``````System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
``````

Some excellent further reading on the topic:

If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.

Specifically, note that `round(200, 0)` returns `200.0`. If you want to output “200.00“, you should first round and then format the result for output (which is perfectly explained in Jesper’s answer).

Questions:

If you just want to print a `double` with two digits after the decimal point, use something like this:

``````double value = 200.3456;
System.out.printf("Value: %.2f", value);
``````

If you want to have the result in a `String` instead of being printed to the console, use `String.format()` with the same arguments:

``````String result = String.format("%.2f", value);
``````

Or use class `DecimalFormat`:

``````DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
``````

Questions:

I think this is easier:

``````double time = 200.3456;
DecimalFormat df = new DecimalFormat("#.##");
time = Double.valueOf(df.format(time));

System.out.println(time); // 200.35
``````

Note that this will actually do the rounding for you, not just formatting.

Questions:

The easiest way, would be to do a trick like this;

``````double val = ....;
val = val*100;
val = Math.round(val);
val = val /100;
``````

if val starts at 200.3456 then it goes to 20034.56 then it gets rounded to 20035 then we divide it to get 200.34.

if you wanted to always round down we could always truncate by casting to an int:

``````double val = ....;
val = val*100;
val = (double)((int) val);
val = val /100;
``````

This technique will work for most cases because for very large doubles (positive or negative) it may overflow. but if you know that your values will be in an appropriate range then this should work for you.

Questions:

``````Precision.round(10.4567, 2)
``````

Questions:
``````function Double round2(Double val) {
return new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue();
}
``````

Note the toString()!!!!

This is because BigDecimal converts the exact binary form of the double!!!

These are the various suggested methods and their fail cases.

``````// Always Good!
new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue()

Double val = 260.775d; //EXPECTED 260.78
260.77 - WRONG - new BigDecimal(val).setScale(2,RoundingMode.HALF_UP).doubleValue()

Double val = 260.775d; //EXPECTED 260.78
260.77 - TRY AGAIN - Math.round(val * 100.d) / 100.0d

Double val = 256.025d; //EXPECTED 256.03d
256.02 - OOPS - new DecimalFormat("0.00").format(val)
// By default use half even, works if you change mode to half_up

Double val = 256.025d; //EXPECTED 256.03d
256.02 - FAIL - (int)(val * 100 + 0.5) / 100.0;
``````

Questions:
``````double value= 200.3456;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(value));
``````

Questions:

If you really want the same double, but rounded in the way you want you can use BigDecimal, for example

``````new BigDecimal(myValue).setScale(2, RoundingMode.HALF_UP).doubleValue();
``````

Questions:
``````double d = 28786.079999999998;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
``````

Questions:

Rounding a double is usually not what one wants. Instead, use `String.format()` to represent it in the desired format.

Questions:

For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.

`x = Math.floor(x * 100) / 100;`

Questions:

in your question it seems that you want to avoid rounding the numbers as well? i think .format() will round the numbers using half-up, afaik?
so if you want rounding, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest… ??:

you could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.

200.3456 * 100 = 20034.56;
(int) 20034.56 = 20034;
20034/100.0 = 200.34;

you might have issues with really really big numbers close to the boundary though. in which case converting to a string and substring’ing it would work just as easily.

Questions:
``````value = (int)(value * 100 + 0.5) / 100.0;