Round Up to 2 Decimal Places in Java

round up to 2 decimal places in java?

Well this one works...

double roundOff = Math.round(a * 100.0) / 100.0;

Output is

123.14

Or as @Rufein said

 double roundOff = (double) Math.round(a * 100) / 100;

this will do it for you as well.

Round a double to 2 decimal places

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.

So, use this instead

(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 = BigDecimal.valueOf(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:

  • Item 48: "Avoid float and double if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch
  • What Every Programmer Should Know About Floating-Point Arithmetic

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).

How do I round a double to two decimal places in Java?

Are you working with money? Creating a String and then converting it back is pretty loopy.

Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.

Even if you're not working with money, consider BigDecimal.

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.

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

EDIT: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:

Double d = n.doubleValue() + 1e-6;

To round down, subtract the accuracy.

How to print a float with 2 decimal places in Java?

You can use the printf method, like so:

System.out.printf("%.2f", val);

In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

There are other conversion characters you can use besides f:

  • d: decimal integer
  • o: octal integer
  • e: floating-point in scientific notation

Problems rounding to 2 decimal places

If you're going to do calculations with your decimal values, you really need to use BigDecimal throughout. Never trust double or float to give accurate answers to calculations involving decimal values.

Also, when you create a BigDecimal from a double, don't use new BigDecimal(yourDouble), because that just puts the floating point error that's already in your double into the BigDecimal. It's generally much better to use BigDecimal.valueOf(yourDouble), which gives you the decimal value with the least number of decimal places that your double is close enough to. That sounds bad, but it's actually good, because you typically get the value that was used to create the double initially.

For example,

System.out.println(new BigDecimal(0.1)); // prints 0.1000000000000000055511151231257827021181583404541015625
System.out.println(BigDecimal.valueOf(0.1)); // prints 0.1

How to round the double value to 2 decimal points?

There's no difference in internal representation between 2 and 2.00. You can use Math.round to round a value to the nearest integer - to make that round to 2 decimal places you could multiply by 100, round, and then divide by 100, but you shouldn't expect the result to be exactly 2dps, due to the nature of binary floating point arithmetic.

If you're only interested in formatting a value to two decimal places, look at DecimalFormat - if you're interested in a number of decimal places while calculating you should really be using BigDecimal. That way you'll know that you really are dealing with decimal digits, rather than "the nearest available double value".

Another option you may want to consider if you're always dealing with two decimal places is to store the value as a long or BigInteger, knowing that it's exactly 100 times the "real" value - effectively storing cents instead of dollars, for example.



Related Topics



Leave a reply



Submit