方法1:用Math.round計算,這里返回的數字格式的.
float price=89.89; int itemNum=3; float totalPrice=price*itemNum; float num=(float)(Math.round(totalPrice*100)/100);//如果要求精確4位就*10000然后/10000
方法2:用DecimalFormat 返回的是String格式的.該類對十進制進行全面的封裝.像%號,千分位,小數精度.科學計算.
float price=1.2; DecimalFormat decimalFormat=new DecimalFormat(".00");//構造方法的字符格式這里如果小數不足2位,會以0補足. String p=decimalFomat.format(price);//format 返回的是字符串
個人覺得在前台顯示金額方面的還是用第二種方式.理由很簡單是字符串格式的.