浮点数(float的有效位数,有效范围理解),使用double不使用float

浮点数(float的有效位数,有效范围理解),使用double不使用float

浮点数

float、double精度范围在使用浮点数时,不要使用float,直接使用double。使用BigDecimal而不用double或long(浮点数运算不安全)

相关精度文章:

float、double精度范围

float、double的精度与范围: float的范围为-2^128 ~ +2^128(-3.40e+38 ~ +3.40e+38) 有效位数:7 double的范围为-2^1024 ~ +2^1024(-1.79e+308 ~ +1.79e+308) 有效位数:16

float: 尾数+数符 24位 阶码+阶符8位 double : 尾数+数符53位 阶码+阶符11位

范围跟阶码有关2的7次方(227)(0为128) 因为是二进制所以幂底数是2 即范围为2128 有效位数:223 (不同编译器不同 大部分为7) 有效位数=没有被约等于 float f = 123456789.1234567f; System.out.println(f); 7后面不准确因此不用算 ,就7位.

在使用浮点数时,不要使用float,直接使用double。

(float放在内存中其实是当作double来处理的,它不会比double更节约内存资源,对应的double虚拟机会直接以double形式来进行处理,快速而且精度高,) https://blog.csdn.net/qq_33101075/article/details/104561797

使用BigDecimal而不用double或long(浮点数运算不安全)

// floating point calculation

final double amount1 = 2.0;

final double amount2 = 1.1;

System.out.println("difference between 2.0 and 1.1 using double is:" + (amount1 - amount2));

// Use BigDecimal for financial calculation

final BigDecimal amount3 = new BigDecimal("2.0");

final BigDecimal amount4 = new BigDecimal("1.1");

System.out.println("difference between 2.0 and 1.1 using BigDecimal is:" + (amount3.subtract(amount4)));

//difference between 2.0 and 1.1 using double is:0.8999999999999999

//difference between 2.0 and 1.1 using BigDecimal is:0.9

为什么会出现这种情况:(个人理解)

十进制转二进制时,2-》10.00 要减1.1 那肯定前面10只能变成01.1111111-1.1(转二进制1.0001100110011…0011)而double只精确到16位。然后再转十进制,就是0.89…99 总共15个9

如果觉得太麻烦可以自己封装: https://blog.csdn.net/Bleach_kids/article/details/49129943

相关推荐

广寒仙子嫦娥皮肤怎么样值得买吗(皮肤价格及特效详解)
twitter注册不了,无法注册推特账号
365赢了不让提款

twitter注册不了,无法注册推特账号

📅 07-15 👁️ 2910
微信限额多久才恢复——让你不再烦恼!
beat365手机app

微信限额多久才恢复——让你不再烦恼!

📅 07-24 👁️ 4405