Java Rounding Issue And Solution

Lets have a look on some fundamentals of mathematics. It is very simple and everyone will recall it.

Rounding in Maths:
Consider we have to round till 4 digits after decimal point

1)  2.41255 will be rounded to  ?????
2) 5.12413  will be rounded to ?????
Answer:
1. 2.4126
2. 5.1241

Above is the maths what we have studied...isnt it? But in JAVA do u know how rounding function works?

if( Do u know how rounding function works in JAVA ?){
   sout(“Skip This”);
}else{
   int val = 29.12455;
   DecimalFormat FourDecimal = new DecimalFormat("###.0000");
   String valStr = FourDecimal.format(val);
   sout (“The Value After Formatting:-”+valStr);
}

Output:
// If(yes)
Skip This
// else
The Value After Formatting :- 29.1245

As per maths what we have studied answer should be 29.1246

Then what is the solution for the above problem?

Here we have solution:
public double roundingForNthDigitIsFive(int afterDecimal , double val) {
   String strBeforeConversion="###.";
   String strAddOne="0."
   while(afterDecimal>0){
      if(afterDecimal==1){
         strAddOne.append("1");
      }else{
         strAddOne.append("0");
      }

      strBeforeConversion.append("0");
      afterDecimal--;
   }
   DecimalFormat decimalFormat = new DecimalFormat(str);
   String valStr =decimalFormat .format(val);
   if (valStr.charAt(valStr.length() - 1) == '5') {
      val = new Double(valStr) + Double.parseDouble(strAddOne);
   }
   return val;
}

Input:
afterDecimal :-  4
val :- 29.12455
Output:
29.1246

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.