9.27
今天学习了Java中数值变量的值
通过学习知道了Java中的浮点数并不为我们所想的准确值
点击查看代码
package Double;
public class DoubleTest {
public static void main(String args[]) {
System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
System.out.println("4.015 * 100 = " + (4.015 * 100));
System.out.println("123.3 / 100 = " + (123.3 / 100));
}
}
点击查看代码
0.05 + 0.01 = 0.060000000000000005
1.0 - 0.42 = 0.5800000000000001
4.015 * 100 = 401.49999999999994
123.3 / 100 = 1.2329999999999999
解决办法为使用BigDecimal类
点击查看代码
package Double;
import java.math.BigDecimal;
public class BigDecimalTest
{
public static void main(String[] args)
{
java.math.BigDecimal f1 = new java.math.BigDecimal("0.05");
java.math.BigDecimal f2 = java.math.BigDecimal.valueOf(0.01);
java.math.BigDecimal f3 = new java.math.BigDecimal(0.05);
System.out.println("使用String构造BigDecimal");
System.out.println("0.05 + 0.01 = " + f1.add(f2));
System.out.println("0.05 - 0.01 = " + f1.subtract(f2));
System.out.println("0.05 * 0.01 = " + f1.multiply(f2));
System.out.println("0.05 / 0.01 = " + f1.divide(f2));
System.out.println("使用double构造BigDecimal");
System.out.println("0.05 + 0.01 = " + f3.add(f2));
System.out.println("0.05 - 0.01 = " + f3.subtract(f2));
System.out.println("0.05 * 0.01 = " + f3.multiply(f2));
System.out.println("0.05 / 0.01 = " + f3.divide(f2));
}
}
点击查看代码
使用String构造BigDecimal
0.05 + 0.01 = 0.06
0.05 - 0.01 = 0.04
0.05 * 0.01 = 0.0005
0.05 / 0.01 = 5
使用double构造BigDecimal
0.05 + 0.01 = 0.06000000000000000277555756156289135105907917022705078125
0.05 - 0.01 = 0.04000000000000000277555756156289135105907917022705078125
0.05 * 0.01 = 0.0005000000000000000277555756156289135105907917022705078125
0.05 / 0.01 = 5.000000000000000277555756156289135105907917022705078125