JAVA怎么计算百分比?

Python014

JAVA怎么计算百分比?,第1张

int num1 = 7  

int num2 = 9  

// 创建一个数值格式化对象

NumberFormat numberFormat = NumberFormat.getInstance()  

// 设置精确到小数点后2位  

public String getPercent(int x,int total){

String result=""//接受百分比的值

double x_double=x*1.0

double tempresult=x/total

numberFormat.setMaximumFractionDigits(2)

String result = numberFormat.format((float) num1 / (float) num2 * 100)  

System.out.println("num1和num2的百分比为:" + result + "%")

比较运算符

比较运算符属于二元运算符,用于程序中的变量之间,变量和自变量之间以及其他类型的信息之间的比较。比较运算符的运算结果是boolean型。当运算符对应的关系成立时,运算的结果为true,否则为false。比较运算符共有6个,通常作为判断的依据用于条件语句中。

Java解释器在没有生成任何对象的情况下,以main作为入口来执行程序。每个类中可以定义多个方法,但main方法只能有一个。关键字public表示访问权限,指明所有的类都可以使用这一方法。

以上内容参考:百度百科-Java

public String getPercent(int x,int total){

String result=""//接受百分比的值

double x_double=x*1.0

double tempresult=x/total

//NumberFormat nf = NumberFormat.getPercentInstance()注释掉的也是一种方法

//nf.setMinimumFractionDigits( 2 ) 保留到小数点后几位

DecimalFormat df1 = new DecimalFormat("0.00%") //##.00% 百分比格式,后面不足2位的用0补齐

//result=nf.format(tempresult)

result= df1.format(tempresult)

return result

}

====================

idehub提供云端手机、平板、pc浏览器等方式的java编程平台,让你随时随地可以编写java代码,并有大神在线解答所有技术问题!关注code4a微信公众号!

运行的结果是

Process started >>>

2  200.00%  1

2  100.00%  2

2  66.67%  3

2  50.00%  4

2  40.00%  5

2  33.33%  6

2  28.57%  7

2  25.00%  8

2  22.22%  9

<<<Process finished. (Exit code 0)