1. 程式人生 > >java中double轉化為百分數

java中double轉化為百分數

1.使用於大多數的情況

import java.text.NumberFormat;

/**
 * Double轉化為百分數
 * @author ganhongliang
 * @date 2018年10月1日
 */
public class DoubleToPercentformat {

	/**
	 * 
	 * @param d
	 * @param IntegerDigits
	 * @param FractionDigits
	 * @return String
	 * @time 2018年10月1日 上午11:09:35
	 */
	public static String getPercentFormat(double d,int IntegerDigits,int FractionDigits){
		  NumberFormat nf = java.text.NumberFormat.getPercentInstance(); 
		  nf.setMaximumIntegerDigits(IntegerDigits);//小數點前保留幾位
		  nf.setMinimumFractionDigits(FractionDigits);// 小數點後保留幾位
		  String str = nf.format(d);
		  return str;
	}
	public static void main(String[] args) {
		System.out.println(getPercentFormat(0.9999, 2, 2));
	}
}

執行結果:99.99%

2.特殊情況:測試0.99999

public static void main(String[] args) {
		System.out.println(getPercentFormat(0.99999, 2, 2));
	}

執行結果:00.00%

結論:當數字大於0.99995,結果都為00.00%