JAVA怎么计算百分比

package com.landray.kmss.tonly.dormitory.forms;

import java.text.NumberFormat;


public class User {
	
	 public static void main(String[] args) {
		  int num1 = 3;
		 int num2 = 11;
		 User.print(num1, num2);
       }

	 static  void print(double num1, double num2)
	  {
		 if(Double.compare(num2, 0) == 0)
		 throw new RuntimeException("输入有误");
		 double ratio = num1 / num2;
		 // 创建一个数值格式化对象  
		 NumberFormat format = NumberFormat.getPercentInstance();
		 //设置保留几位小数
		 format.setMaximumFractionDigits(2);
		 String result=format.format(ratio);
		 System.out.println("百分比为:"+result);
		 
		 
		 double ratioBB=1-ratio;
		 String resultBB=format.format(ratioBB);
		 System.out.println("百分比为:"+resultBB);
		 
       }

}

 

你可能感兴趣的:(Java)