Java数据类型和运算之浮点型变量和BigDecima

带小数的数据在Java中称为浮点型(重要特性就是不精确),浮点型可分为float类型和double类型,double表示这种类型的数值精度约是float类型的两倍,浮点型常量默认类型也是double。

浮点类型常量有两种表示形式

  • 十进制数形式,例如:3.14 314.0 0.314
  • 科学记数法形式,例如:314e2(e2相当于10^2,即314*100) 314E2 314E-2 (3.14)

float:占用4个字节,表数范围:-3.403E38~3.403E38,表示范围大于int,

double:占用8个字节,表数范围:-1.798E308~1.798E308,用的比较多

For Example_01:

package com.Ponfey;

/**
 * 测试浮点型
 * Created by xiaoshuai.zhu on 2020-09-21 14:45
 */

public class TestPrimitiveDataType2 {
    public static void main(String[] args) {
        float a = 3.14F; // float a = 3.14会有报错,3.14是一个浮点型的常量,它的默认类型是double,double是8个字节,要往float里面放,float只有4个字节,放不进去的,后面在写个F,调整整型常量为float
        double b =6.28D; // 这个D可加可不加,无所谓
        double c = 628E-2; // 628* 10^-2=628

        System.out.println(c);

    }
}

For Example_02:

package com.Ponfey;

/**
 * 测试浮点型
 * Created by xiaoshuai.zhu on 2020-09-21 15:07
 */

public class TestPrimitiveDataType2 {
    public static void main(String[] args) {
        //浮点数是不精确的,一定不要用于比较
        float f = 0.1f;
        double d = 1.0/10;
        System.out.println(f==d);//结果为false
    }
}

For Example_03:

package com.Ponfey;

/**
 * 测试浮点型
 * Created by xiaoshuai.zhu on 2020-09-21 15:18
 */

public class TestPrimitiveDataType2 {
    public static void main(String[] args) {

        float d1 = 423432423f;
        float d2 = d1+1;
        if(d1==d2){ //如果它们相等,则...
            System.out.println("d1==d2");//输出结果为d1==d2
        }else{ // 否则...
            System.out.println("d1!=d2");
        }
    }
}

For Example_04:

package com.Ponfey;
import java.math.*; //导入java.math包
/**
 * 测试浮点型
 * Created by xiaoshuai.zhu on 2020-09-21 14:45
 */

public class TestPrimitiveDataType2 {
    public static void main(String[] args) {
            //使用精确的浮点运行,推荐:BigDecimal
            BigDecimal bd = BigDecimal.valueOf(1.0); //bd =1
            bd = bd.subtract(BigDecimal.valueOf(0.1)); //bd 减 0.1
            bd = bd.subtract(BigDecimal.valueOf(0.1)); // 再减0.1
            bd = bd.subtract(BigDecimal.valueOf(0.1));
            bd = bd.subtract(BigDecimal.valueOf(0.1));
            bd = bd.subtract(BigDecimal.valueOf(0.1));
            System.out.println(bd);//0.5
            System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);//0.5000000000000001

            BigDecimal bd2 = BigDecimal.valueOf(0.1);
            BigDecimal bd3 = BigDecimal.valueOf(1.0/10.0);

            System.setOutprintln(bd2.equals(bd3)); // 比较bd2、bd3是否相等
        }
    }
// }
上一篇
下一篇