Math工具类
/**
* @author wcs
* @date 2021/7/29 19:32
*/
public class MathTest01 {
public static void main(String[] args) {
double pi=Math.PI;
System.out.println(pi);
//随机出一个0~1的double类型数字
System.out.println(Math.random());
//Math.round() 四舍五入
System.out.println(Math.round(1.4)); //1
System.out.println(Math.round(1.5)); //2
//Math.floor() 舍去小数
System.out.println(Math.floor(1.3)); //1
System.out.println(Math.floor(1.5)); //1
//Math.ceil() 小数进1
System.out.println(Math.ceil(1.4));//2.0
System.out.println(Math.ceil(1.5));//2.0
//Math.pow() x的y次幂
System.out.println(Math.pow(2,3)); //8
//Math.max(a,b) 最大值 Math.min(a,b) 最小值
System.out.println(Math.max(10,20));//20
System.out.println(Math.min(10,20));//10
}
}
示例:
1、产生一个0~9的随机数
2、输出2021-07-01 00:00:00 到now之间的随机Date
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author wcs
* @date 2021/7/29 19:45
*/
public class MathTest02 {
public static void main(String[] args) throws ParseException {
//产生一个0~9的随机数
int num = (int) Math.round(Math.random() * 9);
System.out.println(num);
//输出2021-07-01 00:00:00 到now之间的随机Date
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = s.parse("2021-07-01 00:00:00");
long start = d.getTime();
long now = System.currentTimeMillis();
//在时间差中产生一个随机数,然后加上起始时间
long time = Math.round(Math.random() * (now - start)) + start;
System.out.println(s.format(time));
}
}
运行结果(随机):
