2008-09-30 16:01:34 8 Comments

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

### Related Questions

#### Sponsored Content

#### 65 Answered Questions

### [SOLVED] Round to at most 2 decimal places (only if necessary)

**2012-08-06 17:17:48****stinkycheeseman****1963851**View**2221**Score**65**Answer- Tags: javascript decimal rounding decimal-point

#### 79 Answered Questions

### [SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

**2008-09-02 20:14:29****user4315****1792171**View**5950**Score**79**Answer- Tags: java methods parameter-passing pass-by-reference pass-by-value

#### 60 Answered Questions

### [SOLVED] How do I read / convert an InputStream into a String in Java?

**2008-11-21 16:47:40****Johnny Maelstrom****1926452**View**3659**Score**60**Answer- Tags: java string io stream inputstream

#### 64 Answered Questions

#### 45 Answered Questions

### [SOLVED] How do I convert a String to an int in Java?

**2011-04-07 18:27:54****Unknown user****5661965**View**2784**Score**45**Answer- Tags: java string int type-conversion

#### 23 Answered Questions

### [SOLVED] Limiting floats to two decimal points

**2009-01-18 18:16:41****kevin****2518306**View**1370**Score**23**Answer- Tags: python floating-point rounding precision

#### 16 Answered Questions

### [SOLVED] Difference between decimal, float and double in .NET?

**2009-03-06 11:31:23****Tom****831223**View**1940**Score**16**Answer- Tags: .net floating-point double decimal

#### 54 Answered Questions

### [SOLVED] Creating a memory leak with Java

**2011-06-24 16:11:52****Mat B.****589715**View**2940**Score**54**Answer- Tags: java memory memory-leaks

## 29 comments

## @MAbraham1 2017-07-27 13:36:33

A succinct solution:

See also, https://stackoverflow.com/a/22186845/212950 Thanks to jpdymond for offering this.

## @Amr Ali 2018-02-13 10:37:22

In general, rounding is done by scaling:

`round(num / p) * p`

## @turbanoff 2019-04-02 22:33:15

What is

`EPSILON`

? It's not defined in the code## @Ivan 2011-07-04 09:10:41

If you really want decimal numbers for calculation (and not only for output), do not use a binary-based floating point format like double.

I do use BigDecimal for calculations, but bear in mind it is dependent on the size of numbers you're dealing with. In most of 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).

## @Elenasys 2018-03-14 17:40:39

To achieve this we can use this formatter:

or:

Use this method to get always two decimals:

Defining this values:

Using the method we can get this results:

demo online.## @Craigo 2018-01-07 07:10:46

If you're using a technology that has a minimal JDK. Here's a way without any Java libs:

## @user207421 2012-10-02 03:18:23

As some others have noted, the correct answer is to use either

`DecimalFormat`

or`BigDecimal`

. Floating-point doesn'thavedecimal 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.

Output of this program:

EDIT:To address some comments below I redid the modulus part of the test loop using`BigDecimal`

and`new MathContext(16)`

for the modulus operation as follows:Result:

## @Didier L 2013-08-09 07:52:02

The trick is that in all of your 9251 errors, the printed result is still correct.

## @user207421 2013-08-11 01:03:08

@DidierL That proves that the 'printed result' and the 'result' aren't the same thing. The correctness of the 'printed result' is affected by what happens during printing. The multiply-and-divide alone doesn't solve the problem.

## @user207421 2013-08-13 09:55:19

@DidierL It doesn't surprise me. I had the very good fortune of doing 'Numerical Methods' as my very first computing course and being introduced right at the start to what floating-point can and cannot do. Most programmers are pretty vague about it.

## @ultrajohn 2013-09-02 05:30:11

the same output was produced by the python version of this program.

## @ultrajohn 2013-09-02 05:46:09

hmm, it seems that there is an error in your program. System.out.println("a="+a+" (a %

.0001)="+(a %0.001));## @Matthieu 2013-10-19 06:04:00

Well, I confess I'm pretty vague about these 'Numerical Methods'. If you have some time, I'd love your insight on an earlier question of mine.

## @Alex 2013-10-25 17:27:07

While the original point stands (truncation of a floating-point is not the same as decimal rounding), this counter-example is a little bit suspect to me. Note that we know the double 0.25 is exactly equal to 1/4, yet

`((0.25 % 0.01) == 0.0)`

evaluates to false.## @Alex 2013-10-25 17:44:16

I would change the test from

`if ((d % 0.01) != 0.0)`

to`if (BigDecimal.valueOf(d).compareTo(new BigDecimal(d)) != 0)`

, which indicates that the error rate is even higher than originally estimated (and increases with the scale, up to 99.9% for a scale of 5)## @Yuri 2013-11-27 12:06:48

There's an explanation: (d % 0.01) adds inaccuracy to the result and shadows the precision of the rounding operation. So it only proves that 92% of the time the modulus operation is not precise. I have a counter example:

`code double d1, d2; d1 = 10.0100000000000000000123D; d2 = 10.0100000D; System.out.println(Math.round(d1 * 100)/100D == d2); // true double d3 = 0.0000090000000000000000000789D; System.out.println(Math.round(d3 * 100)/100D == 0.0D); // true`

BTW, I'm not advocating this technique. It's prone to a possible overflow.## @Peter Lawrey 2014-03-02 11:21:53

All you are doing is refuting that floating doesn't represent many decimal values exactly, which I would hope we all understand. Not that rounding does causes a problem. As you admit, the numbers still print as expected.

## @Peter Lawrey 2014-03-02 11:26:56

Your test is broken, take round() out and the test fails 94% of the time. ideone.com/1y62CY prints

`100 trials 94 errors`

You should start with a test which passes, and show that introducing rounding breaks the test.## @Peter Lawrey 2014-03-02 11:42:36

Refutation, refuted here. Using Math.round for this range of

`double`

as no errors ideone.com/BVCHh3## @user207421 2014-04-03 20:43:54

@PeterLawrey Good point, but it's only true if it's impossible to round .001 to an exact number of decimal places, which is

quod erat demonstrandum.## @hamish 2015-09-04 00:07:51

yeah exactness would mean 100 times more memory usage, and exactness would mean 100 times slower. draw your own conclusions as to why programmers and cpu's love floating point doubles :) in 50 years time when cpu's are 10,000 times faster.. nobody is going to care about doubles anymore :) even now we are seeing faster quad ARM android processors... that is why people already on this thread want exactness over speed.

## @user207421 2016-01-27 03:00:45

@ToolmakerSteve The question is about getting exactly

ndecimal places. Any other result is off-topic, as are your remarks about my attitude.## @user207421 2016-01-27 03:01:33

@hamish It requires a decimal radix, not 100 times more memory.

## @geza 2017-10-05 11:18:05

While I agree with you, as

`0.01`

cannot be represented exactly, this test is bad. A better test would be to convert the result of`roundOff`

to`BigDecimal`

, and compare it to the exact result calculated with`BigDecimal`

.## @user207421 2017-12-18 03:48:18

@geza I redid the loop part using

`BigDecimal/MathContext`

with 16 digits of precision for the modulus part and I got 50% failures.## @chux 2018-02-27 12:56:24

`a *= temp;`

has an imprecision in rounding problem values near a boundary. E.g. x.xx5 and`position == 2`

. The product saved in`a`

incurs a rounding that will result in the wrong`roundOff()`

value from time to time. It would have made more sense here to maintain the extra precision of`double`

with`a = Math.round(a * temp);`

rather than`a *= temp; a = Math.round(a);`

## @marco 2015-11-05 12:54:46

I agree with the chosen answer to use

`DecimalFormat`

--- or alternatively`BigDecimal`

.Please read

Updatebelow first!~~However if you~~dowant 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:Will output

See https://github.com/tools4j/decimal4j/wiki/DoubleRounder-Utility

Disclaimer:I am involved in the decimal4j project.Update:As @iaforek pointed out DoubleRounder sometimes returns counterintuitive results. The reason is that it performs mathematically correct rounding. For instance`DoubleRounder.round(256.025d, 2)`

will be rounded down to 256.02 because the double value represented as 256.025d is somewhat smaller than the rational value 256.025 and hence will be rounded down.Notes:`BigDecimal(double)`

constructor (but not to`valueOf(double)`

which uses the string constructor).For those reasons and everything mentioned above in this post I

cannot recommend to use DoubleRounder.## @iaforek 2017-05-19 14:26:24

Do you have metrics showing how efficient is your solution compared to the other ones?

## @marco 2017-05-19 22:23:09

I haven't compared it with other solutions but there is a jmh benchmark available in the source code: github.com/tools4j/decimal4j/blob/master/src/jmh/java/org/… I did run the benchmark on a VM, the results are available as csv file here: github.com/tools4j/decimal4j/wiki/Performance

## @iaforek 2017-06-01 22:46:17

DoubleRounder fails for following cases: DoubleRounder.round(256.025d, 2) - expected: 256.03, actual: 256.02 or for DoubleRounder.round(260.775d, 2) - expected: 260.78, actual: 260.77.

## @marco 2017-06-11 23:45:04

@iaforek: this is correct, because DoubleRounder performs mathematically correct rounding. However I admit that this is somewhat counterintuitive and will hence update my answer accordingly.

## @MetroidFan2002 2008-09-30 18:33:56

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.Sample program:

## @Etienne Neveu 2010-02-09 10:59:03

That's my preferred solution. Even shorter: BigDecimal.valueOf(doubleVar).setScale(yourScaleHere, BigDecimal.ROUND_HALF_UP); BigDecimal.valueOf(double val) actually calls Double.toString() under the hood ;)

## @Edd 2015-01-26 17:57:29

Nice. Don't cut corners and use

`new BigDecimal(doubleVar)`

as you can run into issues with rounding of floating points## @ToolmakerSteve 2015-08-28 03:41:46

@Edd, interestingly, the rounding issue occurs in the case SebastiaanvandenBroek mentions in comment to asterite's answer.

`double val = 265.335;`

,`BigDecimal.valueOf(val).setScale(decimals, BigDecimal.ROUND_HALF_UP).toPlainString();`

=>`265.34`

, but`(new BigDecimal(val)).setScale(decimals, BigDecimal.ROUND_HALF_UP).toPlainString();`

=>`265.33`

.## @MetroidFan2002 2015-08-30 05:09:41

@ToolmakerSteve That's because using new BigDecimal with the double takes the double value directly and attempts to use that to create the BigDecimal, whereas when using BigDecimal.valueOf or the tostring form parses it to a string first (a more exact representation) before the conversion.

## @Suragch 2017-02-20 14:42:47

I came here just wanting a simple answer on how to round a number. This is a supplemental answer to provide that.

## How to round a number in Java

The most common case is to use

`Math.round()`

.Numbers are rounded to the nearest whole number. A

`.5`

value is rounded up. If you need different rounding behavior than that, you can use one of the other Math functions. See the comparison below.## round

As stated above, this rounds to the nearest whole number.

`.5`

decimals round up. This method returns an`int`

.## ceil

Any decimal value is rounded up to the next integer. It goes to the

ceiling. This method returns a`double`

.## floor

Any decimal value is rounded down to the next integer. This method returns a

`double`

.## rint

This is similar to round in that decimal values round to the closest integer. However, unlike

`round`

,`.5`

values round to the even integer. This method returns a`double`

.## @Suragch 2017-12-03 23:33:40

I got a downvote but I'm not sure what is wrong, so I don't know what to change.

## @lukas84 2019-03-05 10:18:45

you are only solving the particular case of rounding to 0 decimals. The original question is more generic.

## @Suragch 2019-03-05 16:39:43

@lukas84, Ah, right, that explains the downvote, Thanks. I can accept downvotes for that reason. I just wanted to make sure that there were no mistakes in the supplemental code that I provided.

## @Se Song 2016-11-25 09:06:39

DecimalFormat is the best ways to output, but I don't prefer it. I always do this all the time, because it return the double value. So I can use it more than just output.

OR

If you need large decimal places value, you can use BigDecimal instead. Anyways

`.0`

is important. Without it the rounding of 0.33333d5 return 0.33333 and only 9 digits are allows. The second function without`.0`

has problems with 0.30000 return 0.30000000000000004.## @Qamar 2016-11-22 07:36:21

If you Consider 5 or n number of decimal. May be this answer solve your prob.

Output will be:123.01this can be solve with loop and recursive function.

## @Andrei Lupsa 2016-11-10 07:50:39

Since I found no complete answer on this theme I've put together a class that should handle this properly, with support for:

Formatting: Easily format a double to string with a certain number of decimal placesParsing: Parse the formatted value back to doubleLocale: Format and parse using the default localeExponential notation: Start using exponential notation after a certain thresholdUsage is pretty simple:(For the sake of this example I am using a custom locale)

Here is the class:## @pwojnowski 2016-11-10 22:24:26

Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so:

Will print in English locale (no matter what your locale is): 0.99 123.57 123.00

The example is taken from Farenda - how to convert double to String correctly.

## @curtisk 2008-09-30 16:14:15

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:

gives the output:

## @Alex Spurling 2008-10-01 13:07:09

This is probably the best solution presented so far. The reason I didn't spot this facility when I first looked at the DecimalFormat class is that it was only introduced in Java 1.6. Unfortunately I'm restricted to using 1.5 but it will be useful to know for the future.

## @Martin Clemens Bloch 2014-10-15 23:50:10

Doesn't work with exponent decimalformats, say format("0.0E00"). It will in this example round 0.0155 to 0.0E00 instead of 1.6E-02.

## @bigstones 2015-12-11 11:43:18

I tried this with:

`"#.##"`

, rounding`HALF_UP`

.`256.335f`

->`"256.33"`

...(example comes from comments to @asterite's answer).## @Gomino 2016-03-02 17:01:35

Please be carefull as DecimalFormat depend on your current Local configuration, you may not get a dot as a separator. I personnally prefer Asterite's answer below

## @CGK 2016-08-10 03:05:50

Also be aware that you should not expect DecimalFormat to be thread-safe. As per Java docs:

Decimal formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.## @user4919188 2016-10-20 08:00:25

how do i make it so that it does a proper rounding so it will not round 0.0004 to 0.001

## @Thorsten Niehues 2017-12-11 14:20:22

Cannot get this working with HALF_UP: Example

`DecimalFormat df = new DecimalFormat("0.00"); df.setMaximumFractionDigits(2); df.setRoundingMode(RoundingMode.HALF_UP); df.format(3.775)`

returns 3.77## @Dawood ibn Kareem 2018-02-20 02:04:43

It's not too difficult to create cases where this simply doesn't work. I wouldn't use this method if it's important to get the correct result.

## @Asher 2016-03-03 11:43:00

Just in case someone still needs help with this. This solution works perfectly for me.

returns a

`String`

with the desired output.## @asterite 2008-09-30 16:07:24

Assuming

`value`

is a`double`

, you can do:That's for 5 digits precision. The number of zeros indicate the number of decimals.

## @Chris Cudmore 2008-09-30 16:22:46

Math.round uses an internal cast to long, which you are then casting back to double.

## @Andi Jay 2012-07-09 20:01:19

I think this is better than using DecimalFormat though. DecimalFormat will allocate various objects implicitly, and also a String on each call to decimalFormat.Format(). I would image it's better to cast to a few primatives than allocate objects.

## @Andi Jay 2012-07-10 14:35:56

UPDATE: I just confirmed that doing this IS WAY faster than using DecimalFormat. I looped using DecimalFormat 200 times, and this method. DecimalFormat took 14ms to complete the 200 loops, this method took less than 1ms. As I suspected, this is faster. If you get paid by the clock cycle, this is what you should be doing. I'm surprised Chris Cudmore would even say what he said to be honest. allocating objects is always more expensive than casting primitives and using static methods (Math.round() as opposed to decimalFormat.format()).

## @b1nary.atr0phy 2012-08-25 12:33:07

@Andi Jay I'm not saying you're wrong or right, but you can't really say that an isolated test on a single machine confirms your theory.

## @user207421 2012-10-02 03:12:55

This technique fails in over 90% of cases. -1.

## @Robert Tupelo-Schneck 2012-10-03 18:51:09

Indeed, this fails:

`Math.round(0.1 * Math.pow(10,20))/Math.pow(10,20) == 0.09223372036854775`

.## @Alvin Wong 2013-01-15 15:19:45

I think doing multiplication will be faster than division, so

`(double)Math.round(value * 100000) * 0.000001`

## @Victor P. 2013-03-19 22:54:25

I used this method for a long time, but now realized it was not the way to go

## @sambe 2013-08-19 14:18:45

@RobertTupelo-Schneck This does not work, because double only has a precision of approximately 14 decimal places (anything more than that will not be accurate anyway)

## @Matthieu 2013-10-19 05:49:29

@RobertTupelo-Schneck it works up to 10^19 ;)

## @Sebastiaan van den Broek 2013-11-14 13:51:49

Be very careful when using this method (or any rounding of floating points). It fails for something as simple as 265.335. The intermediate result of 265.335 * 100 (precision of 2 digits) is 26533.499999999996. This means it gets rounded down to 265.33. There simply are inherent problems when converting from floating point numbers to real decimal numbers. See EJP's answer here at stackoverflow.com/a/12684082/144578

## @satur9nine 2014-04-10 17:21:18

@ChrisCudmore has the best answer here scroll down now, also Math.pow(10,20) is way too big, if you need 20 decimal places of precision then double is not for you.

## @Matthias Braun 2014-05-19 14:23:43

This fails with very small values too:

`(double)Math.round(1.005 * 100) / 100 == 1.0`

Don't use it!## @hamish 2014-07-13 07:56:31

1.005 == 1.00 and 265.335 == 265.33 -> so what! it is fine. there is conversions of floating point going into round, there is conversions of floating point going into the division, there is floating point conversions going into 100.0 you just have to accept that floating point is FLOATING POINT... it is approximation! of decimals. floating point double is fast!!! sure you lose some precision, but who cares.. its super duper fast!

## @hamish 2014-07-13 08:04:46

sure you lose some tincy wincy precision on the ROUND_EVEN/ROUND_UP on those fringy cases, but who cares.. its super duper fast! that is why programmers use double in the first place. you are rounding those extras off the end anyway so they are obviously not significant to you or your users. otherwise you would not be using double (aka floating point) in the first place.

## @Franz D. 2015-07-15 07:38:10

@AndiJay: "If you get paid by the clock cycle, this is what you should be doing" -- I disagree. If I was paid by clock cycle, I would use the

`DecimalFormat`

to make my code as slow as possible: the more clock cycles it requires, the more money for me ;)## @darren 2015-08-05 17:54:23

for speed, I have converted to an int before where $5.00 became 500. Super fast math, always rounding to 2 decimal points, and display only requires a divide by 100.

## @ToolmakerSteve 2015-08-28 03:17:50

@SebastiaanvandenBroek: Wow I never knew it was that easy to get a wrong answer. However, if one is working with non-exact numbers, one must recognize that any value

is not exact.`265.335`

really means`265.335 += tolerance`

, where tolerance depends on previous operations and range of input values. We do not know the true, exact value.At the edge values,If we need to be exact, we shouldn't work in double. Theeitheranswer is arguably correct.`fail`

here isn't in converting back to double. Its in OP thinking he can rely on the incoming`265.335`

as being exactly that.## @ToolmakerSteve 2015-08-28 16:49:01

oops, that was supposed to read

`+- tolerance`

.## @shmosel 2016-09-08 06:16:09

I don't think the

`(double)`

cast is necessary.## @maaartinus 2017-06-21 04:47:32

@ToolmakerSteve When the initial number has three decimals and you want only two, this gives you the right (

`HALF_EVEN`

rounded) answer:`x = Math.rint(1000*x); x = Math.rint(x/10.0); return x / 100.0;`

. Obviously, the result is not exactly`365.34`

, but it's the closest approximation and it prints out like this.## @user593581 2011-01-28 09:52:24

Suppose you have

you can use

`BigDecimal`

or without BigDecimal

with both solutions

`d == 9232.13`

## @IcedDante 2012-07-16 19:11:42

I think this is the best solution for Java 1.5 users (and below). One comment tho, don't use the HALF_EVEN rounding mode since it has diff behavior for odd and even numbers (2.5 rounds to 2 while 5.5 rounds to 6, for example), unless this is what you want.

## @user207421 2013-03-19 23:27:24

The first solution is correct: the second one doesn't work. See here for proof.

## @Matthias Braun 2014-03-29 00:58:35

@EJP: Even the first solution with

`RoundingMode.HALF_UP`

is wrong. Try it with`1.505`

. The right way is to use`BigDecimal.valueOf(d)`

.## @hamish 2014-07-13 08:22:41

Matthias Braun, the solution is fine, hence 31 ups.. 1.505 decimal is stored in floating point double as 1.50499998 if you want to take 1.505 and convert from double to decimal, then you have to convert it to Double.toString(x) first then put it into a BigDecimal(), but that is extremely slow, and defeats the purpose of using double for speed in the first place.

## @user1114134 2014-07-31 19:32:28

Ran a loop of 100k with BigDecimal (took 225 ms) and Math.round (2 ms) way and here is the timing...Time Taken : 225 milli seconds to convert using to : 9232.13 Time Taken : 2 milli seconds to convert to : 9232.13 techiesinfo.com

## @hamish 2015-09-04 00:00:57

this solution is 112 times slower than other methods. I guess if you do not care about writing fast code, why use a double in the first place. if you want proper base 10 numbers, then NEVER use a double in the first place.

## @Basil Bourque 2015-09-14 22:27:48

@IcedDante The

`HALF_EVEN`

mode is known as “Banker's rounding” often used in financial matters (thus the name). This approach is more fair mathematically than the “Schoolhouse rounding” typically taught to children. Since 5 is exactly in the middle, always rounding up ("Schoolhouse")biases results to larger numbers. Banker's Rounding splits the difference, so half the values round up and half round down (given a random distribution of values).## @stefan.m 2016-02-18 13:18:17

The first solution is also incorrect in a special case: BigDecimal bd = new BigDecimal(12.475d).setScale(2, RoundingMode.HALF_EVEN); bd.doubleValue(); --> Result: 12.47 The correct way would be to do: BigDecimal bd = new BigDecimal(Double.toString(12.475d)).setScale(2, RoundingMode.HALF_EVEN); Reason: new BigDecimal(12.475d) creates a BigDecimal with value 12.4749999999999996447286321199499070644378662109375

## @Dawood ibn Kareem 2018-02-20 03:13:24

You want

`BigDecimal.valueOf(d)`

instead of`new BigDecimal(d)`

if you want to avoid errors due to floating point inaccuracy.## @Mifeet 2015-08-15 15:09:34

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

DecimalFormat#setRoundingMode():

BigDecimal#setScale()

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):Precision from Apache Commons Math

Functions from Colt

Utils from Weka

## @Drew Noakes 2015-06-28 11:54:36

If you're using

`DecimalFormat`

to convert`double`

to`String`

, it's very straightforward:There are several

`RoundingMode`

enum values to select from, depending upon the behaviour you require.## @Easwaramoorthy K 2014-07-22 09:49:35

You can use BigDecimal

Refer: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/

## @aim 2014-04-21 23:51:17

Where

dp= decimal place you want, andvalueis a double.## @Matthias Braun 2014-05-19 14:34:43

Produces

`1.0`

for`value = 1.005`

and`dp = 2`

. Use this instead.## @hamish 2014-07-13 08:15:32

it is ok Matt, your example is not valid. because 1.005 can not be represented in floating point double anyway. it has to stored really above or below 1.005 i.e. it is stored as double when you compile: 1.0049998 (it is not stored as decimal in your compiled code as you would have the readers believe) aim is correct, he is storing values as floating point double, where fringe cases like yours is insignificant anyway. if it was, then you would be using 3dp then converting it to decimal, then doing a decimal round function, just like the link you posted.

## @user207421 2015-06-28 13:02:06

@hamish I don't see where Matthias 'would have the readers believe' any such thing as that the value is compiled as decimal. Don't put words into other people's mouths.

## @Li Ying 2014-02-20 05:04:07

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

See: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html

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

The internal implemetation of this method is:

## @Jasdeep Singh 2011-09-08 11:09:10

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.

## @JibW 2011-09-29 07:01:59

You can use the DecimalFormat class.

## @ecbrodie 2015-12-03 06:25:05

Any reason why

`Double.valueOf()`

was chosen over`Double.parseDouble()`

? The`valueOf()`

method returns a`Double`

object, while`parseDouble()`

will return a`double`

primitive. With the way the current code is written, you also apply auto-unboxing to the return to cast it to the primitive that your`twoDouble`

variable expects, an extra bytecode operation. I'd change the answer to use`parseDouble()`

instead.## @Ryde 2016-05-05 23:40:46

`Double.parseDouble()`

needs`String`

input.## @Ivan 2011-07-03 15:50:51

@Milhous: the decimal format for rounding is excellent:

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:

would return as output:

`0.912385`

would return as output:

`0.91239`

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

## @Paŭlo Ebermann 2011-07-03 19:57:23

If you really want decimal numbers for calculation (and not only for output),

do not use a binary-based floating point formatlike`double`

. Use BigDecimal or any other decimal-based format.## @Amit 2011-04-27 15:56:25

You could use the following utility method-

## @user207421 2013-03-19 23:18:52

Doesn't work, see here for proof.

## @mariolpantunes 2014-02-05 00:55:02

Why do you say it doesn't work? It worked for me.

## @Matthias Braun 2014-03-29 01:02:43

@mariolpantunes: It will fail. Try this:

`round(1.005,2);`

or`round(0.50594724957626620092, 20);`

## @mariolpantunes 2014-03-31 09:04:49

It works. But uninformatively float and doubles are approximations. Let us consider your first example. If you print the output of interestedInZeroDPs before Math.round it will print 100.49999999999999. You lost precision as such Math.round round it as 100. Due to the nature or floats and doubles there are borderlines cases when it does not work properly (more information here en.wikipedia.org/wiki/Floating_point#Accuracy_problems)

## @hamish 2014-07-13 09:16:02

double is a fast! decimal is slow. computers don't bother processing their thinking in decimal notation. you have to give up some decimal precision to keep floating point double fast.

## @user207421 2016-04-25 10:00:46

@hamish The question is about precision, not about speed.

## @Ovesh 2009-09-01 11:14:32

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

## @Milhous 2008-09-30 16:58:12

You can also use the

to make sure you have the trailing 0's.

## @Lunchbox 2012-11-20 20:10:16

I believe one of the goals of the question was that "there should

notbe any trailing zeroes".## @Tom Kincaid 2014-04-08 17:06:39

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.

## @IgorGanapolsky 2015-09-29 21:27:08

You forgot to specify

`RoundingMode.`

## @EndermanAPM 2016-09-27 15:40:01

@IgorGanapolsky by default

`Decimal mode`

uses`RoundingMode.HALF_EVEN.`

## @Chris Cudmore 2008-09-30 16:09:26

## @hamish 2014-07-13 08:39:36

yes this is exactly what math.round does for positive numbers, but have you tried this with negative numbers? people are using math.round in the other solutions to also cover the case of negative numbers.

## @Peter Lawrey 2018-02-02 11:25:30

Note:

`Math.floor(x + 0.5)`

and`Math.round(x)`