3 Replies Latest reply on Jun 26, 2007 8:59 PM by 800435

    Float operation

    807605
      Hello,

      I'm sorry about asking this question again, but I have not found any response clear enough!

      The addition of float primitives do not return an exact value. For example :
      float f1 = 4.8f;
      float f2 = 0.8f;
      System.out.println(f1+f2);
      System.out.println(new BigDecimal(f1).add(new BigDecimal(f2)).floatValue());
      Result :
      5.6000004
      5.6000004


      There is an excellent raison for that, and I don't care about it.
      The true is that this result is false, 4.8 + 0.8 = 5.6

      What is the simplest way for doing that?

      My apologies for my english.
        • 1. Re: Float operation
          807605
          import java.math.*;
          
          public class BigExample {
              public static void main(String[] args) {
                  BigDecimal f1 = new BigDecimal("4.8");
                  BigDecimal f2 = new BigDecimal("0.8");
                  BigDecimal sum = f1.add(f2);
                  System.out.println(sum);
                  BigDecimal sum2 = new BigDecimal("5.6");
                  System.out.println(sum.equals(sum2));
              }
          }
          • 2. Re: Float operation
            807605
            3 ways to get your exact value.
                 float f1 = 4.8f;
                 float f2 = 0.8f;
                 System.out.printf("%.1f%n",f1+f2);
            
                 System.out.println(((f1*10)+(f2*10))/10);
                 System.out.println(new BigDecimal("4.8").add(new BigDecimal("0.8")).floatValue());
            ~Tim
            • 3. Re: Float operation
              800435
              There is an excellent raison for that, and I don't
              care about it.
              But if you are on this business you should care about it. Take a look

              http://docs.sun.com/source/806-3568/ncg_goldberg.html

              Manuel Leiria