public static void percentage_1(){
//這裡的數後面加“D”是表明它是Double類型,否則相除的話取整,無法正常使用
double percent = 50.5D / 150D;
//輸出一下,确認你的小數無誤
System.out.println("小數:" + percent);
//擷取格式化對象
NumberFormat nt = NumberFormat.getPercentInstance();
//設定百分數精确度2即保留兩位小數
nt.setMinimumFractionDigits(2);
//最後格式化并輸出
System.out.println("百分數:" + nt.format(percent));
}
public static void percentage_2(){
NumberFormat formatter = new DecimalFormat("0.000");
Double x=new Double(34.0/55.0);
String xx = formatter.format(x);
System.out.println(xx);
}
public static void main(String[] args) {
percentage_1();
System.out.println("--------------------------");
percentage_2();
}
結果如下:
小數:0.33666666666666667
百分數:33.67%
--------------------------
0.618
引自:[url]http://blog.sina.com.cn/s/blog_9e94b2c1010125v1.html[/url]