本文主要介绍Java 中Math 类,System类,包装类的基本用法。在实际项目开发中我们也会用到这些类,下面我们用代码简单介绍一下。
第一个,Math类。Math类在实际开发中经常用的操作主要有向下取整,向上取整,四舍五入等。
//1. 取绝对值
System.out.println(Math.abs(-9.9));
//2. 向上取整
System.out.println(Math.ceil(10.3));
//3. 向下取整
System.out.println(Math.floor(10.8));
//4. 求指数次方
System.out.println(Math.pow(2,3));
//5. 四舍五入
System.out.println(Math.round(10.7));
第二个, System类。该类可以获取当前的时间戳,进行数组拷贝等功能。
第三个,BigDecimal类,此类可以解决double数据类型运算的时候精度失真的问题。
第四个,包装类,此类可以使得整数和字符串相互转换。
//1. 取绝对值
System.out.println(Math.abs(-9.9));
//2. 向上取整
System.out.println(Math.ceil(10.3));
//3. 向下取整
System.out.println(Math.floor(10.8));
//4. 求指数次方
System.out.println(Math.pow(2,3));
//5. 四舍五入
System.out.println(Math.round(10.7));
//System类获取时间戳
long stamp = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(stamp);
System.out.println(format);
//数组拷贝
int[] a = new int[]{1,2,3,4,5};
int[] b = new int[3];
System.arraycopy(a, 1, b, 1, 2);
for (int i : b) {
System.out.print(i + " ");
}
System.out.println("");
double d1 = 0.1;
double d2 = 0.2;
//此处精度失真
System.out.println(d1 + d2);
//BigDecimal 大数据类,解决double类型精度失真的问题
BigDecimal bd1 = BigDecimal.valueOf(d1);
BigDecimal bd2 = BigDecimal.valueOf(d2);
BigDecimal add = bd1.add(bd2);
System.out.println(add);
//Integer包装类:整数和字符串相互转换
Integer i = 100;
String s = Integer.toString(i);
System.out.println(s);
String str = "10009";
Integer integer = Integer.valueOf(str);
int i1 = Integer.parseInt(str);
System.out.println(integer);
System.out.println(i1);
打印结果如下:
9.9
11.0
10.0
8.0
11
2020-08-10 22:00:57
0 2 3
0.30000000000000004
0.3
100
10009
10009
本文简单介绍了 Java类中Math类,System类,BigDecimal类,包装类的基本使用,在平常的开发过程中也有可能会用到,希望大家能够掌握。