在做頁面層開發時,總是會出現一些要格式化的數字。我總結了一下,在java.text.Format的子類中,可以很好的做這個工作,不過在格式化后,這個數字會變成String,供使用。下面是幾個常用的小技巧:
1.格式化Float ,格式化數字,保留兩位小數
???DecimalFormat doubleFormat = new DecimalFormat();
???//也可以這們初始化:Format formatNum = new java.text.DecimalFormat("##0.00");
???doubleFormat.applyPattern("##0.00");//或者###,###,##0.00
???doubleFormat.format(12.123456);
2.格式化數字,無小數
???DecimalFormat doubleFormat1 = new DecimalFormat();
???doubleFormat1.applyPattern("#");
???doubleFormat1.format(12.123456);
3.格式化日期格式
?SimpleDateFormat formatter
???? = new SimpleDateFormat ("yyyymmdd");
Date currentTime_1 = new Date();
String dateString = formatter.format(currentTime_1);
這是我在開發過程中常用的幾個格式化數字的地方。
更多的技巧:比如說貨幣等,可在下面網頁中尋找解決方法
http://blog.csdn.net/DotJox/archive/2006/07/17/931879.aspx和
http://www.leftworld.net/online/j2sedoc/javaref/增加點js中的格式化吧:
???var n = new Number(thisAccountBalance)
?????div1.innerHTML = n.toFixed(2);
在頁面表現中,要把從jsp取得的數字直接進行計算,然后保留兩位小數,就可以用上面的算法