3

I am trying to format double value to one decimal point using below code but it produces two different rounding values.

 double d1= 4.55;
 double d2= 17.85;
 DecimalFormat oneDForm = new DecimalFormat("#.0");
 System.out.println(oneDForm.format(d1));
 System.out.println(oneDForm.format(d2));

Output: 4.6 17.8 (Expecting 17.9)

But what i wanted roundup by counting up for even decimal 17.85 to 17.9, how to achieve this?

Flogo
  • 1,673
  • 4
  • 20
  • 33
pujari
  • 45
  • 5
  • Do you have full code ? – Prathibha Chiranthana Sep 12 '14 at 07:39
  • 1
    It's a default behaviour, rounding up to even; see http://docs.oracle.com/javase/1.5.0/docs/api/java/math/RoundingMode.html – Dmitry Bychenko Sep 12 '14 at 07:39
  • 1
    Check this:- http://stackoverflow.com/questions/22036885/round-a-double-in-java/22037280#22037280 – Rahul Tripathi Sep 12 '14 at 07:40
  • yes I have. public class Test { public static void main(String[] args) { double d1= 4.55; double d2= 17.85; DecimalFormat oneDForm = new DecimalFormat("#.0"); System.out.println(oneDForm.format(d1)); System.out.println(oneDForm.format(d2)); } } – pujari Sep 12 '14 at 08:23
  • @pujari i believe the information provided in the below answers are valid, but i dont kno y u dint accept any answer, so it might be useful for someone and others dont need to spend time for looking at unanswered questions like this. Y you guys dont understand it. – Vignesh Paramasivam Sep 22 '14 at 09:51

2 Answers2

2

pujari

Default Rounding mode of DecimalFormat uses half-even rounding

According to the document

"Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations. ."

this was also mentioned in

Community
  • 1
  • 1
Prathibha Chiranthana
  • 822
  • 1
  • 10
  • 28
1

To answer your question,

double d1= 4.55;
double d2= 17.85;
DecimalFormat oneDForm = new DecimalFormat("#.0");
oneDForm.setRoundingMode(RoundingMode.HALF_UP); //You're changing default behavior here
System.out.println(oneDForm.format(d1));
System.out.println(oneDForm.format(d2));

you expected output will be : 4.6, 17.9

In my understanding,

You cannot directly roundup17.85 to 17.9 it is the default behavior, and the rounding up works like this, for even decimals it rounds up to least possible digit

Example if its .05,.25,.45.. it will round to .0,.2,.4 and for odd decimal it is the reverse

I believe this one helps to achieve that. This post is a mere resemblance of your post

Community
  • 1
  • 1
Vignesh Paramasivam
  • 2,360
  • 5
  • 26
  • 57