欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浮点数运算的精度问题(BigDecimal运算)

程序员文章站 2022-04-08 14:57:00
...
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();
   }
}

 

相关标签: UP