java-编码笔记-计算百分比(保留两位小数)

1.代码 

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class BaiFenBi2 {
    public static void main(String[] args) {
	BaiFenBi2 bf = new BaiFenBi2();
	bf.main();
    }
    public static void out(String str){
	System.out.println(str);
    }
    public void main(){
	getPercent0(17,108);
	getPercent1(17,108);
	getPercent2(17,108);
	getPercent3(17,107);
    }
    // String的format方法
    public void getPercent0(double x, double total){
	double tempresult = x*100/ total;
	out(String.format("%.2f", tempresult)+"%");
    }
    // DecimalFormat
    public void getPercent1(double x, double total) {
	String result = "";// 接受百分比的值
	double tempresult = x*100/ total;
	DecimalFormat df1 = new DecimalFormat("00.00");
	result = df1.format(tempresult)+"%";
	out(result);
    }
    //BigDecimal的setScale方法
    public void getPercent2(double x, double total){
	double f =  x*100/ total;
	BigDecimal bg = new BigDecimal(f);
	double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	out(f1+"%");
    }
    //NumberFormat的setMaximumFractionDigits方法
    public void getPercent3(double x, double total){
	double f =  x*100/ total;

	NumberFormat nf = NumberFormat.getNumberInstance();
	nf.setMaximumFractionDigits(2);
	System.out.println(nf.format(f)+"%");
    }
    

}

2.运行结果

你可能感兴趣的:(java-编码笔记)