Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6967256

Java.math.BigDecimal reading 5.675 as 5.67499999999

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 6
    • core-libs
    • x86
    • windows_xp

      FULL PRODUCT VERSION :
      java version 1.5.0_12

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows XP [Version 5.1.2600]

      A DESCRIPTION OF THE PROBLEM :
      Java.math.BigDecimal reading 5.675 as 5.67499999999.

      I have tried the following code snippet -


      public static void main(String[] args) {
      double number = 5.675;
      Double d = new Double(number);
      BigDecimal bd = new BigDecimal(number);
      bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
      System.out.println(bd.toString());
      }


      I am getting the response as 5.67, whereas it should be 5.68.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Please run the code snippet in Description section to reproduce the scenario.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Should get the result as 5.68
      ACTUAL -
      5.67 is coming instead.

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      public static void main(String[] args) {
      double number = 5.675;
      Double d = new Double(number);
      BigDecimal bd = new BigDecimal(number);
      bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
      System.out.println(bd.toString());
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      We can do the rounding manually -

      public class DoubleOperation {

      private static int ROUND_HALF_UP = 4;

      public static BigDecimal setScale(Double number, int precision, int mode){
      String numberString = number.toString();
      int decimalIndex = numberString.indexOf('.');
      numberString = numberString.substring(0, decimalIndex + precision + 2);
      BigDecimal num = new BigDecimal(numberString);
      System.out.println(Integer.parseInt(numberString.substring(numberString.length() - 1)));

      if(mode == ROUND_HALF_UP){
      if(Integer.parseInt(numberString.substring(numberString.length() - 1)) >= 5){
      num = num.setScale(precision, BigDecimal.ROUND_CEILING);
      }else{
      num = num.setScale(precision, BigDecimal.ROUND_FLOOR);
      }
      }

      return num;
      }

      }

            darcy Joe Darcy
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: