如下是我寫的一段代碼:
public class NumberTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(formatDouble(5.225));
System.out.println(formatDouble(5.226));
System.out.println(formatDouble(5.2251));
}
private static String formatDouble(double data)
{
String ret = null;
try {
NumberFormat form = NumberFormat.getInstance();
String mask = "###0.00";
((DecimalFormat)form).applyPattern(mask);
ret = form.format(data);
} catch (Exception e) {
e.printStackTrace();
ret = null;
}
return ret;
}
}
輸出結果為:
5.22
5.23
5.23
為什麼第一個沒有四捨五入呢???
formatNumber標簽使用的是4捨6入5奇偶"的算法. 要實現"四捨五入",只需要在原有值的基礎上再加一個比較小的值即可:
"4捨6入5奇偶":
System.out.println(formatDouble(5.225));
"4捨5入":
System.out.println(formatDouble(5.225+0.0001));