浮動小数点数演算の精度問題(BigDecimal演算)

1632 ワード

import java.math.BigDecimal;

public class test {

 public static void main(String[] args) {
  float a = 1.1f;
  float b = 2.2f;
   test t = new test ();
   System.out.println(t.add(a,b));
   System.out.println(t.sub(a,b));
   System.out.println(t.mul(a,b));
   System.out.println(t.div(a,b));
   System.out.println(t.round(a));

 }
 public float add(float v1,float v2){// 
    BigDecimal b1 = new BigDecimal(Float.toString(v1));
    BigDecimal b2 = new BigDecimal(Float.toString(v2));
   return b1.add(b2).floatValue();
   }

  public float sub(float v1,float v2){// 
    BigDecimal b1 = new BigDecimal(Float.toString(v1));
    BigDecimal b2 = new BigDecimal(Float.toString(v2));
   return b1.subtract(b2).floatValue();
   }

  public float mul(float v1,float v2){// 
    BigDecimal b1 = new BigDecimal(Float.toString(v1));
    BigDecimal b2 = new BigDecimal(Float.toString(v2));
   return b1.multiply(b2).floatValue();
   }

  public float div(float v1,float v2){// 
    BigDecimal b1 = new BigDecimal(Float.toString(v1));
    BigDecimal b2 = new BigDecimal(Float.toString(v2));
   return b1.divide(b2,3,BigDecimal.ROUND_HALF_UP).floatValue();
   }

  public float round(float v){// 3 
    BigDecimal b = new BigDecimal(Float.toString(v));
    BigDecimal one = new BigDecimal("1");
   return b.divide(one,3,BigDecimal.ROUND_HALF_UP).floatValue();
   }
}