3 Replies Latest reply on Oct 2, 2008 5:10 PM by 807589

    Issue with BigDecimal.ROUND_HALF_UP

    807589
      Hi,

      I am having a bit of an issue with BigDecimal ROUND_HALF_UP

      For example:

      BigDecimal result = new BigDecimal(212.325).setScale(2, BigDecimal.ROUND_HALF_UP);

      Expected answer = 212.33
      Actual answer = 212.32

      This contradicts the JAVA api

      Any ideas?

      I am using JDK 1.4.2_16-b05

      Thanks
      Brian

      Edited by: ChrisMoltisanti on Oct 2, 2008 9:08 AM
        • 1. Re: Issue with BigDecimal.ROUND_HALF_UP
          807589
          BigDecimal result = new BigDecimal("212.325").setScale(2, BigDecimal.ROUND_HALF_UP);
          In case you are wondering why - with the original the literal number, 212.325 is first converted to a double but there is no exact IEEE format representation for 212.325 so it gets as close as it can which is probably just less than 212.325. When you use a String literal to specify the value there is always an exact representation.

          Edited by: sabre150 on Oct 2, 2008 5:13 PM
          • 2. Re: Issue with BigDecimal.ROUND_HALF_UP
            807589
            Thanks fo yuor reply.
            I ran some unit tests and can confirm that passing in a double does not give an acurate figure.
            Passing it in as a string fixes this.

            Thanks

            Chris
            • 3. Re: Issue with BigDecimal.ROUND_HALF_UP
              807589
              ChrisMoltisanti wrote:
              Passing it in as a string fixes this.
              Note that the APIfor [BigDecimal(double)|http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(double)] states this clearly:

              <quote>
              The results of this constructor can be somewhat unpredictable.
              ...
              The String constructor, on the other hand, is perfectly predictable
              </quote>

              Lesson: learn the API; read the API.