天天看點

[Java基礎] Java float保留兩位小數或多位小數

方法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 傳回的是字元串      

 個人覺得在前台顯示金額方面的還是用第二種方式.理由很簡單是字元串格式的.