JAVA-Math中以下常用方法以及获取随机数和给定一个数获取保留两位小数

注、在Math中有非常多我们平时对数据操作发方法:详情请查看jdk->java.Lang->Math

1、我在这里列举几个:

//在math中常用的一些方法
	public static void SetMath(){
		double ceil = Math.ceil(16.34);//Cell返回大于指定数据的最小整数   17.0
		sop(ceil);
		double floor = Math.floor(12.52);//floor返回小于指定数据的最小整数  12.0
		sop(floor);
		long round = Math.round(13.51); //四舍五入
		sop(round);
		double pow = Math.pow(2, 3); //pow(double a, double b); 表示2的3次幂  8.0
		sop(pow);
	}
	
	public static void sop(Object obj){
		System.out.println(obj);
	}



2、使用Math方法中的Random方法获取随机数

//使用Math中random方法获取随机数

	public static void SetMathRandom(){
		for (int i = 0; i < 10; i++) {
			int s = (int)(Math.random()*10+1); //因为Math.random()方法获取到的是0.0到1.0之前的小数但是又不包括1是所有要加1
			System.out.print(s+",");
		}
	}
3、使用Util包下的Random类获取随机数

//使用Util包下的Random类实现随机数
	public static void SetUrtlRandom(){
		Random random = new Random();
		for (int i = 0; i < 10; i++) {
			int nextInt = random.nextInt(10)+1; //因为nextInt(10);方法表示从0到10但是不包括10
			System.out.print(nextInt+",");
		}
	}

4、练习:获取小数后两位小数

/*
	 * 练习:给定一个小数,保留小数的后两位
	 * 	下面给出四种方法
	 */
	public static void Demo(Double price){
		
		BigDecimal bg = new BigDecimal(price);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println(f1);
        
        //DecimalFormat转换最简便
		DecimalFormat decimalFormat =new DecimalFormat("#.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p= decimalFormat.format(price);//format 返回的是字符串
		System.out.println(p);
		
		//String.format打印最简便
		String format = String.format("%.2f", price);
		System.out.println(format);
		
		 NumberFormat nf = NumberFormat.getNumberInstance();
         nf.setMaximumFractionDigits(2);
         String format2 = nf.format(price);
         System.out.println(format2);
		
	}






  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值